Thursday, 3 November 2011

Entity Framework Eager Loading: Using Strongly-Typed LINQ Include statements

Using Entity Framework to query a database...often need to Eager Load child collections if you want to use them to select parent records.

You can build up your query dynamically and then hit the database once...instead of once for each criterion.

I often see a lot of people using strings to denote which child entities to eager load.

I feel it's much better to use the Strongly Typed syntax.

So if you have:
var query = _orderRepository.Context.CreateObjectSet("CBD_SITES")

you can convert it to:
var query = _orderRepository.GetQuery()
 .Include(h => h.ORDER_DETAIL.Select(t => t.PRODUCT))
 .Include(h => h.ADDRESS);

I got the syntax for the Include statement from this post on Stack Overflow

To understand how to load related entities, in Entity Framework, read this article:

Using DbContext in EF 4.1 Part 6: Loading Related Entities

This post also makes for interesting reading about a related problem.

FYI: If you're wondering what the '_orderRepository' object above is all about, it is an Instance of our custom Repository<TEntity> class, which implements our custom IRepository<TEntity> interface (which in turn implements IDisposable)

...the Repository acts as a wrapper to System.Data.Objects.ObjectContext from the Entity Framework.

We do this so we can use StructureMap in inject a Repository<TEntity> into our Controllers at runtime where TEnity is the Model for that Controller.

So, all '_orderRepository.GetQuery()' does is wraps up and returns the property

System.Data.Objects.ObjectContext.ObjectSet as Queryable

No comments:

Post a Comment