Revisiting the Repository and Unit of Work Patterns with Entity Framework
2013-08-07 11:33
549 查看
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 Framework.
methods for adding and removing an 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:
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:
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:
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:
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:
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.
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.
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 Framework.
Revisiting The Repositoy Implementation
In the Repository pattern, I added to the interface two newmethods 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 aUnit 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 naiveexample 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.
相关文章推荐
- Using Repository and Unit of Work patterns with Entity Framework 4.0
- Using Repository and Unit of Work patterns with Entity Framework 4.0
- Generic repository pattern and Unit of work with Entity framework
- Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application (9 of 10)
- [转]Using the Repository Pattern with ASP.NET MVC and Entity Framework
- Using the Repository Pattern with ASP.NET MVC and Entity Framework
- [转]Sorting, Filtering, and Paging with the Entity Framework in an ASP.NET MVC Application (3 of 10)
- MVC 5 Scaffolder + EntityFramework+UnitOfWork Pattern 代码生成工具
- MVC UnitOfWork EntityFramework架构,网站速度慢的原因总结!
- Sorting, Filtering, and Paging with the Entity Framework in an ASP.NET MVC Application
- MVC 5 Scaffolder + EntityFramework+UnitOfWork Pattern 代码生成工具集成Visual Studio 2013
- Server-Side Paging with the Entity Framework and ASP.NET MVC 3
- Professional ADO.NET 3.5 with LINQ and the Entity Framework
- 海洋工作室——网站建设专家:The version of SQL Server in use does not support datatype datetime2 and the Entity Framework.
- MVC3+EF4.1学习系列(八)-----利用Repository and Unit of Work重构项目
- MVC UnitOfWork EntityFramework架构,网站速度慢的原因总结!
- Repository Pattern with Entity Framework 4.1 and Code First
- MVC3+EF4.1学习系列(八)-----利用Repository and Unit of Work重构项目
- MVC UnitOfWork EntityFramework架构
- Configuring Autofac to work with the ASP.NET Identity Framework in MVC 5