Repository pattern with Entity Frameworks 4
I used to use NHibernate with repository 开发者_开发知识库interfaces.
What is the proper way to use this pattern with EF?
How can I implement this repository interface, for aRepositoryBase<T>
?
public interface IRepository<T>
{
T GetById(object id);
void Save(T entity);
T[] GetAll();
void Delete(T entity);
}
For some reason all of the examples given expose the collections as IQueryable or IEnumerable. EF4 has an interface for this very purpose - IObjectSet (or IDbSet if you're using the latest CTP).
Julie Lerman has a tremendous post on doing this, including creating a MockSet that implements IObjectSet, so you can do some disconnected unit testing
http://thedatafarm.com/blog/data-access/agile-entity-framework-4-repository-part-6-mocks-amp-unit-tests/
It's not really a whole lot different than any other ORM. Here's an example: http://blogs.microsoft.co.il/blogs/gilf/archive/2010/01/20/using-repository-pattern-with-entity-framework.aspx
Have a look at the Entity Framework Repository & Unit of Work Template. You have some details here.
There are several approaches (most of them are quite similar and only differ slightly), so I would recommend doing some research and choosing which one suits you best.
With EF 4 it is possible to implement a generic repository by using ObjectSet<T>
. Take a look at a few articles that might help:
http://devtalk.dk/2009/06/09/Entity+Framework+40+Beta+1+POCO+ObjectSet+Repository+And+UnitOfWork.aspx
http://www.forkcan.com/viewcode/166/Generic-Entity-Framework-40-Base-Repository
You basically have your Repositories talk yo your object context. Only change I would make would be having your GetAll return an IEnumerable instead something like:
public class SomeObjectRepo : IRepository<SomeObject>
{
SomeContext GetById(object id)
{
using(var context = new MyContext())
{
return context.SomeObjects.First(x=>x.id.Equals(id));
}
}
etc...
}
This is my solution: http://www.necronet.org/archive/2010/04/10/generic-repository-for-entity-framework.aspx
I like this because it doesn't couple instance of repository with specific instance of object context, so with some DI framework, I can have all my repositories be singletons.
精彩评论