我有以下查询:
var MyQuery = from e in ContractContext.Equipments.Include("Manufacturers")
where e.Customers.ID == customer.ID
select e;
一切正常,我得到了我的设备,它正确地(急切地)加载了 Manufacturers 表。但是当我尝试执行以下多对多查询时:
var MyQuery = from e in ContractContext.Equipments.Include("Manufacturers")
where e.Customers.ID == customer.ID
from cce in e.ContractEquipments
where cce.Contracts.EndedOn >= DateTime.Today
select e;
其中“ContractEquipments”是“Equipments”和“Contracts”之间的多对多查找,但是当此查询运行时,不再轻松加载 Manufacturers 表。知道如何在不执行以下操作的情况下解决此问题:
if (MyEntity.Manufacturers.IsLoaded == false)
MyEntity.ManufacturersReference.Load()
这个项目需要几个小时才能执行,我想减少数据库调用的次数。
编辑#1:
我也试过没有成功:
var MyQuery = from e in ContractContext.Equipments.Include("Manufacturers")
where e.Customers.ID == customer.ID
join cce in ContractContext.ContractEquipments
on e.ID equals cce.Equipments.ID
where cce.Contracts.EndedOn >= DateTime.Today
select e;
最佳答案
早期包含通常会在某些类型的查询中迷失方向(即额外连接等)
解决这个问题的方法是进行查询,(然后只要您返回实体即选择 e 而不是投影即选择新{...})您可以转换为 ObjectQuery 并执行包含在外面:
var MyQuery = ((from e in ContractContext.Equipments
where e.Customers.ID == customer.ID
from cce in e.ContractEquipments
where cce.Contracts.EndedOn >= DateTime.Today
select e) as ObjectQuery<Equipment>).Include("Manufacturers");
这应该有效。
如果您对这方面的更多信息感兴趣,请查看 Tip 22 - How to make Include really Include
亚历克斯
关于c# - LINQ to Entity Framework 多对多预加载问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/936558/