LINQ包含子项的值错误 [英] LINQ Include Values of children error

查看:79
本文介绍了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语句,但这不会导致任何地方.如果我做到这一点:

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.

推荐答案

Include有很多幻想.其中之一是,如果在应用查询形状后将其更改,则会忽略Include.这发生在您的情况下.如果查询如下所示,Inlude将起作用:

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

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

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

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

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

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

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")

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

这篇关于LINQ包含子项的值错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆