- Agile Entity Framework 4 Repository: Part 1- Model and POCO Classes
- Agile Entity Framework 4 Repository: Part 2- The Repository
- Agile EF4 Repository: Part 3 -Fine Tuning the Repository
- Agile EF4 Repository: Part 4: Compiled LINQ Queries
- Agile Entity Framework 4 Repository Part 5: IObjectSet and Include
- Agile Entity Framework 4 Repository: Part 6: Mocks & Unit Tests
In Part 2 of this blog series, I created a context interface, IBAGAContext, that returns IObjectSet types rather than ObjectSet types from the EntitySets.
Example:
IObjectSet<Contact> Contacts{get;}
IObjectSet<Customer> Customers {get;}
IObjectSet is the new EF4 interface that is used to create the ObjectSets returned by the default context.
For a point of comparison, here’s a method from a default code generated context:
public ObjectSet<Activity> Activities { get { if ((_Activities == null)) { _Activities = base.CreateObjectSet<Activity>("Activities"); } return _Activities; } } private ObjectSet<Activity> _Activities;
ObjectSet implements IObjectSet which provides it with set operations. It also inherits from QueryObject which gives it lots of EF capabilities. One of the methods that come with QueryObject is Include which provides eager loading.
context.Customers.Include(“Orders”) blah blah
(A few people, including Matthieu Mezil, have created overloads for Include that take lambdas instead of magic strings. Here’s Matthieu’s second of two posts which contains a link to the first: Entity Framework Include with Function Next. Additionally, Jamie Philips had a lambda function for EF1 that allowed further filtering. Last time we talked, he reported that it wasn’t working with EF4 POCOs.)
But Include is not available with IObjectSet.
In a recent comment, Nick asked how I was using Include on an IObjectSet.I realize I neglected to add that into the relevant post.
With nods to Jamie Phillips again, Include came from his POCO sample when he and I co-presented back-to-back EF4 POCO sessions at the New England Code Camp in October.
Jamie created an Include extension method to replace the Include supplied by the ObjectQuery. I placed the method in a separate class file in the same project that contains the model and the BAGAContext file because it simply calls the real ObjectQuery.Include.
namespace ExtensionMethods { public static class MyExtensions { public static IQueryable<TSource> Include<TSource> (this IQueryable<TSource> source, string path) { var objectQuery = source as ObjectQuery<TSource>; if (objectQuery != null) { return objectQuery.Include(path); } return source; } } }
In the repositories in Part 3 of this series, this is how I was able to use the Include method.
Jamie did write a follow-up post about the problem with the lambdas and POCO classes: Include() Extension Method and POCO