[英]problem with navigation properties in entity framework
当我执行此查询时,我可以在TypeP
属性中导航:
var items = from item in context.ProductosBodegas.Include("Product.TypeP")
select item;
但是当我执行此查询时, TypeP
属性为null
:
var items = from item in context.ProductosBodegas.Include("Product.TypeP")
select item.Product;
为什么是这样?
看起来Include只会影响直接返回的对象:
http://msdn.microsoft.com/en-us/library/bb896272.aspx
否则你可以打电话
item.TypePReference.Load()
但如果在循环中使用,这可能(并且将会)导致性能问题(N + 1选择)。
假设Product和ProductosBodegas之间的关系是双向的,那么另一种选择是“反转”您的查询:
var items = context.Products
.Include("TypeP")
.Where(p => p.ProductosBodegas.Any( /* include condition here if needed */ ))
据我所知,实体框架只要您不想返回完整实体而只返回投影,就会忽略包含。 例如,请参阅此处的答案。 我不确定这对所有类型的预测是否仍然有效,但显然它在您的情况下仍然有效。
您可以通过将要加载的导航属性添加到匿名类型来解决此问题:
var items = from item in context.ProductosBodegas
select new {
Product = item.Product,
TypeP = item.Product.TypeP
};
(你不需要.Include
here。)执行这个查询后(例如使用.ToList()
)你可以只投射到你想拥有的匿名类型的部分,如下所示:
var products = items.ToList().Select(x => x.Product);
此products
集合中的元素现在已加载TypeP
引用属性。
编辑:
重要说明:请勿更改.ToList
和.Select...
的顺序。 虽然这......
var products = items.Select(x => x.Product).ToList();
...在语法上也是正确的,并且还返回产品的枚举,在这种情况下不会加载TypeP
引用。 必须首先在数据库中执行匿名类型的查询,并将anoynmous类型集合加载到内存中。 然后你可以通过.Select
方法丢弃你不想拥有的anoynmous类型的部分。
你应该先加载产品
var items = from item in context.ProductosBodegas.Include("Product").Include("Product.TypeP")
select item;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.