LINQ to Entity Framework许多渴望加载问题 [英] LINQ to Entity Framework Many-Many Eager Loading issue

查看:87
本文介绍了LINQ to Entity Framework许多渴望加载问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下查询:

var MyQuery = from e in ContractContext.Equipments.Include("Manufacturers")
              where e.Customers.ID == customer.ID
              select e;

一切正常,我得到我的设备,它正确地加载了Manufacturers表(热切地)。但是当我尝试执行以下多对多查询时:

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;

其中ContractEquipments是设备和合同之间的多对多查找,但是,当查询运行时,制造商表不再容易加载。任何想法如何解决这个问题而不做以下事情:

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.

编辑#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;


推荐答案

早期包含往往迷失在某些类型的查询即使用额外的连接等)

Early includes often get lost on some types of queries (i.e. with extra joins etc)

解决这个问题的方法是执行查询(然后只要你返回实体,即选择e而不是投影即选择新的{...}),您可以转换为ObjectQuery并在外部执行包含:

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:

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");

这应该可以工作。

如果你对此有更多信息感兴趣,请查看提示22 - 如何使包含真正包含

If you are interested in more info on this, check out Tip 22 - How to make Include really Include

Alex

这篇关于LINQ to Entity Framework许多渴望加载问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆