开发者

problem with navigation properties in entity framework

When I execute this query I can navigate in TypeP property:

var items = from item in context.ProductosBodegas.Include("Product.TypeP")
            select item;

But when I execute this 开发者_开发知识库query the TypeP Property is null:

var items = from item in context.ProductosBodegas.Include("Product.TypeP")
            select item.Product;

Why is this?


Looks like Include only affects the directly returned object :

http://msdn.microsoft.com/en-us/library/bb896272.aspx

Otherwise you can call

item.TypePReference.Load()

But this can (and will) lead to perfornance issues (N+1 select), if used in a loop.

Another option would be to "reverse" your query, assuming relationship between Product and ProductosBodegas is bidirectional :

var items = context.Products
    .Include("TypeP")
    .Where(p => p.ProductosBodegas.Any( /* include condition here if needed */ ))


As far as I know Entity Framework ignores Includes as soon as you don't want to return full entities but only projections. See for instance the answer here. I am not sure if that is still valid for all types of projections but apparently it is still valid in your situation.

You can workaround this by adding the navigation property you want to have loaded into an anonymous type:

var items = from item in context.ProductosBodegas
            select new {
                Product = item.Product,
                TypeP = item.Product.TypeP
            };

(You don't need .Include here anymore.) After executing this query (by using .ToList() for instance) you can project to only the part of the anonymous type you want to have, like so:

var products = items.ToList().Select(x => x.Product);

The elements in this products collection have loaded the TypeP reference property now.

Edit:

Important note: Don't change the order of .ToList and .Select.... While this ...

var products = items.Select(x => x.Product).ToList();

... is also syntactically correct and also returns an enumeration of products, the TypeP reference will NOT be loaded in this case. The query for the anonymous type must be executed at first in the database and the anoynmous type collection loaded into memory. Then you can throw away the part of the anoynmous type you don't want to have by the .Select method.


you should load product first

var items = from item in context.ProductosBodegas.Include("Product").Include("Product.TypeP")
            select item;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜