【问题标题】:LINQ Include Values of children errorLINQ 包含子错误的值
【发布时间】:2016-10-06 21:36:17
【问题描述】:

我有这个问题:

var allValues = from p in _pContext.Persons
where p.Id == currentPerson.Id
from i in p.Items //This is a list that contains "Items"
select i;

我想拥有所有项目和它们包含的所有嵌套值。执行此查询时如何加载这些?我知道我可以在上下文中使用包含语句,但这不会导致任何地方。如果我这样做:

var allValues = from p in _pContext.Persons.Include("Items.Properties")
where p.Id == currentPerson.Id
from i in p.Items //This is a list that contains "Items"
select i;

要加载所有项目及其关联的“属性”,这些属性未加载,它们的列表已实例化但不包含任何内容。

【问题讨论】:

  • 不同版本的 Include 方法确实存在于不同的类中。那个接受一个 lamda,您可以在其中指定要包含的相关对象。据我所知,您需要使用:using System.Data.Entity; 才能使用。
  • 人与物品之间有一对多的关系吗?
  • 对不起,我不能使用 lambda 表达式,因为我正在使用 MySQL 和 EF,据我所知,它不支持包含的 lambda 表达式。

标签: c# entity-framework linq nested-queries


【解决方案1】:

Include 有很多令人迷惑的怪癖。其中之一是如果查询形状在应用后发生更改,则会忽略Include。这发生在你的情况下。如果查询如下所示,Inlude 有效:

from p in _pContext.Persons.Include("Items.Properties")
select p

这是因为路径 "Items.Properties" 可以从最终结果的实体中遍历出来:Person

但是现在您通过更改返回的实体来更改查询的形状...

from p in _pContext.Persons.Include("Items.Properties")
from i in p.Items
select i

... 并且包含路径不再有效。 (不能从Item 遍历)。

对于Include,有一个简单的经验法则:在查询结束时应用它。这样做,您将自动输入正确的路径,尤其是。当你使用 lambda 语法时:

(from p in _pContext.Persons
from i in p.Items
select i).Include("Properties")

(from p in _pContext.Persons
from i in p.Items
select i).Include(i => i.Properties)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    相关资源
    最近更新 更多