我正在尝试确定如何使用EntityFramework 计算表上的匹配行。
问题在于每一行可能有许多兆字节的数据(在二进制字段中)。当然,SQL应该是这样的:
SELECT COUNT(*) FROM [MyTable] WHERE [fkID] = '1';
我可以加载所有行,然后找到Count:
var owner = context.MyContainer.Where(t => t.ID == '1');
owner.MyTable.Load();
var count = owner.MyTable.Count();
但这是完全无效的。有没有更简单的方法?
编辑:谢谢,所有。我已将数据库从专用附件中移出,以便可以进行性能分析;这会有所帮助,但会引起我意想不到的混乱。
而我的真实数据是深一点,我会用卡车运送托盘的案件的资料 -我不想让卡车离开除非有至少一个项目在里面。
我的尝试如下所示。我不了解的部分是CASE_2从不访问DB服务器(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中可以看到,Truck-Pallet和Pallet-Case关系是多对多的-尽管我认为这并不重要。我的真实物品是无形物品,很难描述,因此我更改了名称。]