Click here to Skip to main content
15,881,413 members
Articles / Entity Framework

Revisiting the Repository and Unit of Work Patterns with Entity Framework

Rate me:
Please Sign up or sign in to vote.
4.00/5 (4 votes)
18 Jul 2010CPOL2 min read 39.8K   14   7
In the past I wrote two posts about the Repository and the Unit of Work patterns (here and here). Today I want to show a better and less naive solution for imposing the Unit of Work and the Repository patterns with Entity Frame

In the past I wrote two posts about the Repository and the Unit of Work patterns (here and here). Today I want to show a better and less naive solution for imposingthe Unit of Work and the Repository patterns with Entity Framework.

Revisiting The Repositoy Implementation

In the Repository pattern, I added to the interface two new methods for adding and removing an entity:

public interface IRepository<T>
                where T : class
{
  T GetById(int id);
  IEnumerable<T> GetAll();
  IEnumerable<T> Query(Expression<Func<T, bool>> filter);    
  void Add(T entity);
  void Remove(T entity);
}

Also I’ve changed the return type of the Query from IQueryable to IEnumerable in order not to enable additional composition on that query that will hit the database. The implementation of the Repository itself will change as follows:

public abstract class Repository<T> : IRepository<T>
                                  where T : class
{
  #region Members
 
  protected IObjectSet<T> _objectSet;
 
  #endregion
 
  #region Ctor
 
  public Repository(ObjectContext context)
  {
    _objectSet = context.CreateObjectSet<T>();
  }
 
  #endregion
 
  #region IRepository<T> Members
 
  public IEnumerable<T> GetAll()
  {
    return _objectSet;
  }
 
  public abstract T GetById(int id);
 
  public IEnumerable<T> Query(Expression<Func<T, bool>> filter)
  {
    return _objectSet.Where(filter);
  }
 
  public void Add(T entity)
  {
    _objectSet.AddObject(entity);
  }
 
  public void Remove(T entity)
  {
    _objectSet.DeleteObject(entity);
  }
 
  #endregion

One of the things to notice is that I hold an IObjectSet as my data  member of the Repository itself instead of holding the context like in my previous post. The IObjectSet is a new interface in EF4 which helps to abstract the use of the created entity sets. Now the Repository is better implemented and looks like an in-memory collection as it was suppose to be. If I need more specific methods I can inherit from this Repository implementation and add the desired functionality. As you can see I don’t implement the GetById method and enforce my concretes to implement it. The DepartmentRepository from the previous post will look like:

public class DepartmentRepository : Repository<Department>
{
   #region Ctor
 
   public DepartmentRepository(ObjectContext context)
     : base(context)
   {
   }
 
   #endregion
 
   #region Methods
 
   public override Department GetById(int id)
   {
     return _objectSet.SingleOrDefault(e => e.DepartmentID == id);
   }
 
   #endregion
}

Revisiting The Unit of Work Implementation

After we have our Repository we would like to create a Unit of Work to hold the application repositories and to orchestrate the persisting of data for some business transactions. The new interface for the Unit of Work will look like:

public interface IUnitOfWork
{
  IRepository<Department> Departments { get; }    
  void Commit();
}

By of course if you have more repositories in your application you will add them to the IUnitOfWork (in the example I only have the departments repository). Now the implementation of the Unit of Work won’t be a part of the repository (like in the old post) and will look like:

public class UnitOfWork : IUnitOfWork
{
  #region Members
 
  private readonly ObjectContext _context;
  private DepartmentRepository _departments;
 
  #endregion
 
  #region Ctor
 
  public UnitOfWork(ObjectContext context)
  {
    if (context == null)
    {
      throw new ArgumentNullException("context wasn't supplied");
    }
 
    _context = context;
  }
 
  #endregion
 
  #region IUnitOfWork Members
 
  public IRepository<Department> Departments
  {
    get
    {
      if (_departments == null)
      {
        _departments = new DepartmentRepository(_context);
      }
      return _departments;
 
    }
  }
 
  public void Commit()
  {
    _context.SaveChanges();
  }
 
  #endregion
}

As can be seen the Unit of Work holds the ObjectContext but you could use an IContext interface instead if you like to be more abstract and with no dependency on Entity Framework at all. This can be achieved by using the T4 templates that were provided in EF4 which you will use to add the IContext interface implementation. The Unit of Work has a constructor that can be injected using an IoC container. The testing program will change into:

using (SchoolEntities context = new SchoolEntities())
{
  UnitOfWork uow = new UnitOfWork(context);
  foreach (var department in uow.Departments.GetAll())
  {
    Console.WriteLine(department.Name);
  }
 
  foreach (var department in uow.Departments.Query(d => d.Budget > 150000))
  {
    Console.WriteLine("department with above 150000 budget: {0}",
        department.Name);
  }
}

Some thing to notice here is that I create the context during the running of the program. As I wrote earlier, this can be changed to using an IoC container instead which will inject the constructor dependency.

Summary

Lets sum up, this offered solution is much better then the naive example I gave in the previous posts. It is much more testable and abstract and as I wrote you could go further and use an IoC container to inject the use of Entity Framework in the Unit of Work implementation.

This article was originally posted at http://feeds.feedburner.com/GilFinkBlog

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead sparXys
Israel Israel
Gil Fink is a web development expert and ASP.Net/IIS Microsoft MVP. He is the founder and owner of sparXys. He is currently consulting for various enterprises and companies, where he helps to develop Web and RIA-based solutions. He conducts lectures and workshops for individuals and enterprises who want to specialize in infrastructure and web development. He is also co-author of several Microsoft Official Courses (MOCs) and training kits, co-author of "Pro Single Page Application Development" book (Apress) and the founder of Front-End.IL Meetup. You can read his publications at his website: http://www.gilfink.net

Comments and Discussions

 
Generalloading child entities Pin
Blue Clouds1-Jul-12 4:45
Blue Clouds1-Jul-12 4:45 
GeneralRe: loading child entities Pin
Gil Fink1-Jul-12 21:03
Gil Fink1-Jul-12 21:03 
QuestionUse a purely generic respository... Pin
Baslifico10-Mar-12 15:36
Baslifico10-Mar-12 15:36 
QuestionUpdate Entity Pin
JorgeVinagre1-Mar-12 14:50
JorgeVinagre1-Mar-12 14:50 
GeneralDon't ! There is no need ... Pin
User 171854111-Nov-10 6:15
User 171854111-Nov-10 6:15 
... for the UoW to know anything about repositories, daos, whatever - and vice versa. You even make it a repository factory. That's a rather separate concern, isn't it?

Just wrap your favorite underlaying object/data/framework-context and stick a GO_TELL_THE_DB_TO_EAT_ALL_OR_NOTHING_OF_THIS-button on it. Or make it an IDisposable, auto-committing all pending changes on finalisation. Add some failure handling too, e.g. Hibernate wants a brand-new context then.

P.S. How about giving it another try?
GeneralMy vote of 4 Pin
Alberto Manzanilla8-Sep-10 17:50
Alberto Manzanilla8-Sep-10 17:50 
GeneralMy vote of 1 Pin
zdlik3-Aug-10 17:48
zdlik3-Aug-10 17:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.