LINQ包含子项值的错误
我有这个问题:
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;
我想拥有它们包含的所有项目和所有嵌套值。 如何在执行此查询时加载这些? 我知道我可以在上下文中使用include语句,但这并不能引导任何地方。 如果我这样做:
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
有很多妄想怪癖。 其中之一是如果查询形状在应用后发生更改,则忽略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)