Pablogrind
Pablogrind

Reputation: 457

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?

Upvotes: 3

Views: 2602

Answers (3)

saber safavi
saber safavi

Reputation: 452

you should load product first

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

Upvotes: 1

Slauma
Slauma

Reputation: 177163

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.

Upvotes: 2

mathieu
mathieu

Reputation: 31202

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 */ ))

Upvotes: 4

Related Questions