LINQ to Entity Framework 多对多预加载问题
我有以下查询:
var MyQuery = from e in ContractContext.Equipments.Include("Manufacturers")
where e.Customers.ID == customer.ID
select e;
一切正常,我得到了我的设备,并且它正确地(热切地)加载了制造商表。 但是,当我尝试执行以下多对多查询时:
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”之间的多对多查找,但是当此查询运行时,制造商表不再容易加载。 知道如何在不执行以下操作的情况下解决此问题:
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;
I have the following query:
var MyQuery = from e in ContractContext.Equipments.Include("Manufacturers")
where e.Customers.ID == customer.ID
select e;
And everything works, I get my Equipments and it loads the Manufacturers table correctly (eagerly). But when I try to do the following many-to-many query:
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;
where "ContractEquipments" is a many-to-many lookup between "Equipments" and "Contracts", but when this query runs, the Manufacturers table no longer gets easily loaded. Any idea how to fix this without doing the following:
if (MyEntity.Manufacturers.IsLoaded == false)
MyEntity.ManufacturersReference.Load()
This project takes hours execute and I want to keep the number of database calls down.
EDIT #1:
I also tried this without success:
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
早期包含经常会在某些类型的查询中迷失(即使用额外的联接等)。
解决这个问题的方法是执行查询,(然后只要您返回实体,即选择 e 而不是投影,即选择新的 { ...})您可以转换为 ObjectQuery 并在外部进行包含:
这应该可行。
如果您对此感兴趣,请查看 提示 22 - 如何使 Include 真正包含
Alex
Early includes often get lost on some types of queries (i.e. with extra joins etc)
The way to get around this is to do the query, (and then so long as you are returning entities i.e. Select e rather than a projection i.e. Select new {...}) you can cast to ObjectQuery and do the include around the outside:
This should work.
If you are interested in more info on this, check out Tip 22 - How to make Include really Include
Alex
您是否尝试过像这样加入?
Have you tried a join instead like this?