Adventures with the Entity Framework and the Repository Pattern

Posted by Martyn at 8/20/2009 1:09:32 AM

Tags: Patterns | EntityFramework

So far in my applications, I have been using the Entity Framework for object persistence (why? SQLite is why).  Unfortunately, I also like to write lots of unit tests.  Normally, this would be a problem, as the entity container would be coupled to the controllers.

How I implement the Repository Pattern

To get around this, I have been using the repository pattern to great effect.

I start by creating my IRepository<T> generic interface:

   1:      public interface IRepository<T>
   2:      {
   3:          T Single(Func<T, bool> filter);
   4:          IQueryable<T> All { get; }
   5:   
   6:          void Insert(T entity);
   7:          void Remove(T entity);
   8:   
   9:          void Commit();
  10:      }

People could say that the Single method is rather pointless, but I like to have it there.  You could also comment on the lack of an Update method – but the entity framework’s change tracking does a good job.  Other people would say this is bad, as the repository is being tied to the entity framework, but that is not the reason I am doing this.

Originally, I would have an interface per entity, but the generic interface solves all the duplication I was seeing.

This interface is extremely simple to implement, and solves my Entity Framework + TDD problems.

Regardless, roll on EF 4.0 POCOs!

Lambda42 © Copyright 2010. All Rights Reserved.