Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

Revisiting the Repository and Unit of Work Patterns with Entity Framework

, 18 Jul 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

Gil Fink
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
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
Generalloading child entities PinmemberBlue Clouds1-Jul-12 5:45 
There is context.ContextOptions.LazyLoadingEnabled option
but what if we want to work on repostory level to optionally load some entities and not all.
 
eg:
Person GerPersonbyId(int id)
{
}
 
how could we ensure that Person.Address is loaded as well( in just Person repostory)?
 

in the repository implementation all we have is 'IObjectSet _objectSet' and not ObjectContext.
 
Hence context.Include(x => x.Address)
or context.Loadproperty won't work
GeneralRe: loading child entities PinmemberGil Fink1-Jul-12 22:03 
QuestionUse a purely generic respository... PinmemberMember 358373110-Mar-12 16:36 
QuestionUpdate Entity PinmemberJorgeVinagre1-Mar-12 15:50 
GeneralDon't ! There is no need ... Pinmemberapplerobot11-Nov-10 7:15 
GeneralMy vote of 4 PinmemberAlberto Manzanilla8-Sep-10 18:50 
GeneralMy vote of 1 Pinmemberzdlik3-Aug-10 18:48 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.1411028.1 | Last Updated 18 Jul 2010
Article Copyright 2010 by Gil Fink
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid