2016-10-04 50 views
0

我有这个疑问: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; 

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

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; 

得到装载它们相关联的“属性”的所有物品,这些性能的arent装,他们的名单被实例化,但它不包含任何。

+0

不同版本的包括法确实在不同的类存在。那个人接受一个lamda,在那里你指定要包含的相关对象。据我所知,你需要使用:'使用System.Data.Entity;'才能使用。 – Max

+0

你有人与物品之间的一对多关系吗? – octavioccl

+0

对不起,我不能使用lambda表达式,因为我使用的是EF,它不支持包含lambda表达式的MySQL,据我所知。 – Ravior

回答

2

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)