Hi all, i'm writing an asp.net mvc 2 web application with Entity Framework 4.0. I have the views that should display items, views that are for login, etc. Should i structure the project with a repository pattern? If yes, how? Should i create an interface for basics methods like Add, Update, Delete, etc and another class that use the repository for the common methods like login validation, etc?
I use EF with the repository pattern, it saves me hell a lot of work!
Small Respository Pattern Intro:
someRepository.Find.Where(something => something.IsRed && something.IsBig)
Create a generic interface called 'IRepository' of type containing all the methods for data access.
It could look like this:
interface IRepository<T> where T : class
{
IEnumerable<T> FindAll(Func<T, bool> exp);
T FindSingle(Func<T, bool> exp);
}
Create an abstract 'Repository' class implementing this interface:
class Repository<T> : IRepository<T> where T : class
{
TestDataContext _dataContext = TestDataContext(); // Would be your EF Context
public IEnumerable<T> FindAll(Func<T, bool> exp)
{
_dataContext.GetTable<T>().Where<T>(exp);
}
public T FindSingle(Func<T, bool> exp)
{
_dataContext.GetTable<T>().Single(exp);
}
}
We can now create an interface for the something
table/objects which implements our 'IRepository' and a concrete class extending the abstract 'Repository' class and implementing the 'ISomethingInterface':
interface ISomethingRepository : IRepository<Banner>
{
}
And the matching repository to implement it:
class SeomthingRepository : Repository<Banner>, IBannerRepository
{
}
I would suggest using this approach as it gives you a lot of flexibility as well as enough power to control all the tiny entities you have.
Calling those methods will be super easy that way:
SomethingRepository _repo = new SomethingRepository ();
_repo.Find.Where(something => something.IsRed && something.IsBig)
Yes, it means that you have to do some work but it is hell easier for you to change the data source later on.
Hope it helps!
The most complete answer you can get is probably here:
http://huyrua.wordpress.com/2010/07/13/entity-framework-4-poco-repository-and-specification-pattern/
Quite a lot to read and figure out, but if you really want to understand how to use the repository pattern with EF, that's probably the most complete source.
Some simpler sample code to get a quickstart can be found here:
http://www.forkcan.com/viewcode/166/Generic-Entity-Framework-40-Base-Repository
You can also find different variation + discussions (e.g. whether it's a good idea to return IQueryable's
from the repository, etc.