Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework - Navigating and Including properties through collections

I've just had a massive *blonde moment**, but it's highlighted an annoyance I have with Entity Framework. I have disabled lazy loading so I'm forcing myself to actually think about what data I require in order to keep the application as fast as possible.

So in order to return data within a query, I need to make use of the Include method:

var query = from item in context.Customers
                .Include(x=> x.Orders)
            select item

This is fine until I want to select an item a bit deeper into the hierarchy. I.e:

Customer 1-* Orders *-1 Factory 1-1 Factory Type

As far as I know, the only way to return all this data eagerly would be to do the following:

var query = from item in context.Customers
                .Include("Orders.Factory.FactoryType")
            select item

With the above I'm unable to make use of the System.Data.Entity Lambdas as per my first example. Does anyone know if I'm missing something obvious here, or am I stuck with using string declarations for my navigation properties through collections?

If I didn't have any collections, I could just write:

.Include(x=> x.Order.OrderType.Factory.FactoryType) // No bother

But because of the Orders collection, there's no way to step through to a child property as far as I can tell (FirstOrDefault, SingleOrDefault, etc, do not work).


**it's just a turn-of-phrase, I happen to be very fond of blondes*

like image 486
djdd87 Avatar asked Sep 23 '10 16:09

djdd87


People also ask

What is the use of navigation property in Entity Framework?

A navigation property is an optional property on an entity type that allows for navigation from one end of an association to the other end. Unlike other properties, navigation properties do not carry data.

What is navigation properties in Entity Framework Core?

Navigation property: A property defined on the principal and/or dependent entity that references the related entity. Collection navigation property: A navigation property that contains references to many related entities.

What are scalar and navigation properties in Entity Framework?

Basically a scalar property is mapped to a column (int, string, ...) A navigation property is mapped to a relation. e.g Order. OrderDetails brings you to all ORderDetails of a specific order.


1 Answers

For including EntityCollections you use the Select method:

var query = from item in context.Customers
           .Include(c => c.Orders.Select(o => o.Factory.FactoryType))
           select item

Please note that this is not an overload of the standard ObjectQuery<T>.Include Method and is merely an extension method on ObjectQuery<T> Class coming with EF CTP4.

like image 59
Morteza Manavi Avatar answered Sep 29 '22 13:09

Morteza Manavi