Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / entity-framework

Revisiting the Repository and Unit of Work Patterns with Entity Framework

4.00/5 (4 votes)
18 Jul 2010CPOL2 min read 40.5K  
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.

License

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