Monday, January 27, 2014

Generic Repositories Including Includes!

The real credit for this solution goes to Steve Moss. He posted this article last year:

All that I've done is modified his work to fit in with the generic repository pattern that I often use.

One of the difficulties in using a repository to manage your data is that the repository itself can end up obscuring functionality from the underlying data provider. The pattern that I previously wrote about did just this. If you needed to Include relationships that were not originally established in your entity model, you had to create additional logic to retrieve that missing data.

As the Entity Framework has matured, the support for Including data from related entities has improved. Specifically, since EF 4.1, you can use strongly typed lambda's to specify relationships to eagerly load data. This, in combination with the existing string "Include", make working with entity relationships much more convenient.

To extend the original repository pattern to support dynamic includes, all that has to be done is to add an additional Select overload to the repository interface, and then make a quick change to the base class and the child classes that implement it.

1. Update the interface definition. The overloaded Select method that accepts an array of Expressions is the key.
public interface IRepository : IDisposable
    void Insert<E>(E entity) where E : class;

    void Update<E>(E entity) where E : class;

    void Delete<E>(E entity) where E : class;

    IQueryable<E> Select<E>() where E : class;

    IQueryable<E> Select<E>(params Expression<Func<E, object>>[] includeExpressions) where E : class;

    E Select<E>(object key) where E : class;