LINQ Include Values of children error

为君一笑 提交于 2019-12-02 15:59:39

问题


I have this query:

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;

I want to have all the Items and all the nested values that they contain. How do I load these when executing this query, too? I know theres the include statement that I can use on the context, but that doesnt lead anywhere. If I f.e. do this:

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;

to get all the items loaded with their associated "Properties", these properties arent loaded, their list is instanciated but it doesnt contains any.


回答1:


Include has lots of delusive quirks. One of them is that an Include is ignored if the query shape changes after it is applied. This happens in your case. The Inlude works if the query looks like this:

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

This is because the path "Items.Properties" is traversable off of the entity in the end result: Person.

But now you change the shape of the query by changing the returned entity...

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

... and the include path is no longer valid. (Not traversable off of Item).

For Include there's a simple rule of the thumb: apply it at the end of the query. Doing that, you'll automatically enter the correct path, esp. when you use lambda syntax:

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

or

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


来源:https://stackoverflow.com/questions/39858207/linq-include-values-of-children-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!