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*
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With