c# - LINQ to Entity Framework 多对多预加载问题

标签 c# .net linq entity-framework eager-loading

我有以下查询:

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/

相关文章:

c# - 获取所有可能的单词组合

c# - 在与 STL 混合的 C# 中调用非托管 C++ 代码

c# - 什么是NullReferenceException,如何解决?

c# - LINQ 查询上的 foreach() 速度慢 - ToList() 极大地提高了性能 - 为什么会这样?

c# - .NET 正则表达式分组 : Exclude String from group

c# - 如何在EF Core Code First中创建枚举对应的表?

c# - System.Net.Mail.SmtpClient 在发送电子邮件时使用什么类型的身份验证?

c# - .WPF 应用程序生成 <appname>.dll.config 而不是 <appname>.exe.config

c# - Linq 查询中的意外结果总是 + 1

c# - 如何使用 Action 过滤器更改输入参数