我试图确定如何使用 EntityFramework 对表中的匹配行进行 统计。
问题是每行可能有许多兆字节的数据(在 Binary 字段中)。当然,SQL 是这样的:
SELECT COUNT(*) FROM [MyTable] WHERE [fkID] = '1';
我可以加载所有的行和 那么找到伯爵:
var owner = context.MyContainer.Where(t => t.ID == '1');
owner.MyTable.Load();
var count = owner.MyTable.Count();
但这种方法效率极低,有更简单的方法吗?
编辑: 谢谢大家。我已经将数据库从一个私有附件中移除,这样我就可以运行分析; 这有所帮助,但会造成我没有预料到的混乱。
我的实际数据比较深入,我将使用 卡车携带 物品的 案件的 托盘——我不希望 卡车离开,除非它至少有一个 物品。
我的尝试如下所示。我没有得到的部分是 CASE _ 2从来没有访问数据库服务器(MSSQL)。
var truck = context.Truck.FirstOrDefault(t => (t.ID == truckID));
if (truck == null)
return "Invalid Truck ID: " + truckID;
var dlist = from t in ve.Truck
where t.ID == truckID
select t.Driver;
if (dlist.Count() == 0)
return "No Driver for this Truck";
var plist = from t in ve.Truck where t.ID == truckID
from r in t.Pallet select r;
if (plist.Count() == 0)
return "No Pallets are in this Truck";
#if CASE_1
/// This works fine (using 'plist'):
var list1 = from r in plist
from c in r.Case
from i in c.Item
select i;
if (list1.Count() == 0)
return "No Items are in the Truck";
#endif
#if CASE_2
/// This never executes any SQL on the server.
var list2 = from r in truck.Pallet
from c in r.Case
from i in c.Item
select i;
bool ok = (list.Count() > 0);
if (!ok)
return "No Items are in the Truck";
#endif
#if CASE_3
/// Forced loading also works, as stated in the OP...
bool ok = false;
foreach (var pallet in truck.Pallet) {
pallet.Case.Load();
foreach (var kase in pallet.Case) {
kase.Item.Load();
var item = kase.Item.FirstOrDefault();
if (item != null) {
ok = true;
break;
}
}
if (ok) break;
}
if (!ok)
return "No Items are in the Truck";
#endif
由 CASE _ 1产生的 SQL 通过 Sp _ Executesql传输,但是:
SELECT [Project1].[C1] AS [C1]
FROM ( SELECT cast(1 as bit) AS X ) AS [SingleRowTable1]
LEFT OUTER JOIN (SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
COUNT(cast(1 as bit)) AS [A1]
FROM [dbo].[PalletTruckMap] AS [Extent1]
INNER JOIN [dbo].[PalletCaseMap] AS [Extent2] ON [Extent1].[PalletID] = [Extent2].[PalletID]
INNER JOIN [dbo].[Item] AS [Extent3] ON [Extent2].[CaseID] = [Extent3].[CaseID]
WHERE [Extent1].[TruckID] = '....'
) AS [GroupBy1] ) AS [Project1] ON 1 = 1
[ 我真的没有卡车,司机,托盘,箱子或项目,正如你可以看到从 SQL 卡车托盘和 Pallet-Case 的关系是多对多-虽然我不认为这有什么关系。我的真实物品是无形的,很难描述,所以我改了名字。]