The Repository Pattern is a common construct to avoid duplication of data access logic throughout our application. This includes direct access to a database, ORM, WCF dataservices, xml files and so on. The sole purpose of the repository is to hide the nitty gritty details of accessing the data. We can easily query the repository for data objects, without having to know how to provide things like a connection string. The repository behaves like a freely available in-memory data collection to which we can add, delete and update objects.
The Repository pattern adds a separation layer between the data and domain layers of an application. It also makes the data access parts of an application better testable.
You can download or view the solution sources on GitHub:
LINQ to SQL version (the code from this example)
Entity Framework code first version (added at the end of this post)
The example below show an interface of a generic repository of type T, which is a LINQ to SQL entity. It provides a basic interface with operations like Insert, Delete, GetById and GetAll. The SearchFor operation takes a lambda expression predicate to query for a specific entity.
using System; using System.Linq; using System.Linq.Expressions; namespace Remondo.Database.Repositories { public interface IRepository<T> { void Insert(T entity); void Delete(T entity); IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate); IQueryable<T> GetAll(); T GetById(int id); } }
The implementation of the IRepository interface is pretty straight forward. In the constructor we retrieve the repository entity by calling the datacontext GetTable(of type T) method. The resulting Table(of type T) is the entity table we work with in the rest of the class methods. e.g. SearchFor() simply calls the Where operator on the table with the predicate provided.
using System; using System.Data.Linq; using System.Linq; using System.Linq.Expressions; namespace Remondo.Database.Repositories { public class Repository<T> : IRepository<T> where T : class, IEntity { protected Table<T> DataTable; public Repository(DataContext dataContext) { DataTable = dataContext.GetTable<T>(); } #region IRepository<T> Members public void Insert(T entity) { DataTable.InsertOnSubmit(entity); } public void Delete(T entity) { DataTable.DeleteOnSubmit(entity); } public IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate) { return DataTable.Where(predicate); } public IQueryable<T> GetAll() { return DataTable; } public T GetById(int id) { // Sidenote: the == operator throws NotSupported Exception! // 'The Mapping of Interface Member is not supported' // Use .Equals() instead return DataTable.Single(e => e.ID.Equals(id)); } #endregion } }
The generic GetById() method explicitly needs all our entities to implement the IEntity interface. This is because we need them to provide us with an Id property to make our generic search for a specific Id possible.
namespace Remondo.Database { public interface IEntity { int ID { get; } } }
Since we already have LINQ to SQL entities with an Id property, declaring the IEntity interface is sufficient. Since these are partial classes, they will not be overridden by LINQ to SQL code generation tools.
namespace Remondo.Database { partial class City : IEntity { } partial class Hotel : IEntity { } }
We are now ready to use the generic repository in an application.
using System; using System.Collections.Generic; using System.Linq; using Remondo.Database; using Remondo.Database.Repositories; namespace LinqToSqlRepositoryConsole { internal class Program { private static void Main() { using (var dataContext = new HotelsDataContext()) { var hotelRepository = new Repository<Hotel>(dataContext); var cityRepository = new Repository<City>(dataContext); City city = cityRepository .SearchFor(c => c.Name.StartsWith("Ams")) .Single(); IEnumerable<Hotel> orderedHotels = hotelRepository .GetAll() .Where(c => c.City.Equals(city)) .OrderBy(h => h.Name); Console.WriteLine("* Hotels in {0} *", city.Name); foreach (Hotel orderedHotel in orderedHotels) { Console.WriteLine(orderedHotel.Name); } Console.ReadKey(); } } } }
Once we get of the generic path into more entity specific operations we can create an implementation for that entity based on the generic version. In the example below we construct a HotelRepository with an entity specific GetHotelsByCity() method. You get the idea. ;-)
using System.Data.Linq; using System.Linq; namespace Remondo.Database.Repositories { public class HotelRepository : Repository<Hotel>, IHotelRepository { public HotelRepository(DataContext dataContext) : base(dataContext) { } public IQueryable<Hotel> FindHotelsByCity(City city) { return DataTable.Where(h => h.City.Equals(city)); } } }
[Update juli 2012] Entity Framework version
The code below shows a nice and clean implementation of the generic repository pattern for the Entity Framework. There’s no need for the IEntity interface here since we use the convenient Find extension method of the DbSet class. Thanks to my co-worker Frank van der Geld for helping me out.
using System; using System.Data.Entity; using System.Linq; using System.Linq.Expressions; namespace Remondo.Database.Repositories { public class Repository<T> : IRepository<T> where T : class { protected DbSet<T> DbSet; public Repository(DbContext dataContext) { DbSet = dataContext.Set<T>(); } #region IRepository<T> Members public void Insert(T entity) { DbSet.Add(entity); } public void Delete(T entity) { DbSet.Remove(entity); } public IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate) { return DbSet.Where(predicate); } public IQueryable<T> GetAll() { return DbSet; } public T GetById(int id) { return DbSet.Find(id); } #endregion } }


Can you provide an example to use this with EF?
Btw, awesome blog. I really enjoy it. Found it today and bookmarked. :-)
Jan
You’re welcome sir ;-)
I added an Entity Framework Based example to the repository.
Great design on http://janhartmann.dk/ Your work I presume?
The generic repository pattern for EF looks a lot like this one.I’ll try to post it tonight.
I added an update to the post juli 2012 with a generic repository pattern for Entity Framework.
cheers
After reading your article i realized i’m still a novice at programming
Very interesting congrats! bookmarked.
And so am I… but thanks :-)
Great Blog. Bookmarked !
Thanks bhavana. Hope to see you again :-)
very helpful.
thanks
You’re welcome Reza.
Google should built a better translator so we all could read the poems(?) on your blog.
really very helpful for us…
thanks..
You’re welcome Gaurav.
Nice article for noob like me.
GREAT JOB.
TYVM,
Ayi
Thanks. Only a smart programmer recognizes knowledge gaps. We all are noobs in some way :-)
Beautiful!
One question. How would you use the class HotelRepository in your app knowing that it only understands types implementing interface IRepository. When using methods of IHotelRepository I will first need to cast it to that interface right?
Thanks!!
I’m not sure if I understand your question correctly Zeek, but did you mean a HotelRepository implementation like the one below? No casting needed for IRepository.
Thank you! I was a bit sleepy and didn’t see that in my mind. =)
Sorry to wake you up ;-)
Nice Article.
Can this Repository Pattern be implemented without using EF, Linq to SQL and other ORM mapping? I mean, Can it be done with Ado.Net and POCO?
Hi Rajkumar,
This pattern is aimed towards entity framework or linq to sql.
But a more generic pattern is could be usefull for all kinds of data access.
An example without an ORM backend would be great. There’s never been a time in my career that using an ORM has been acceptable. Having to bang against Stored Procs are the only way any large scale enterprise will let data be accessed. Care to show us a real world example of such a thing?
Good article, thanks.
What are other EF related patterns beside the repository pattern, which i may have missed? And why should i use the repository pattern instead of ‘them’?
Hi Chris,
A pattern is not directly related to a technique. You see them everywhere. One of the most important ‘other’ patterns used in Entity Framework is the Unit of Work. See the ObjectContext Class as an example. But you can use the Unit of Work whenever you need to persist data in transactions and have to deal with concurrency problems.
You use the repository pattern as a layer of abstraction between a datasource and business logic. We can simply call something like CustomerRepository.GetAll() and we don’t care how we get those customers. That’s the repository’s job. If you ever need to change the way you retrieve customers, there’s no need to change code other than inside the repository and everything still works like a charm.
Thank you Leon. ‘I see a bit clearer now.’
Great article. Can you post the code for this? I am trying to create the app based on your code, but it has missing components like HotelsDataContext etc.
thanks heaps!
There ya go… Download or view this solution on GitHub:
Great work. Looking a implementing this with a current library. However the objects use a combination of the object name and id, ex, FooId, and BarId. How would I implement your example with this id naming convention?
I added a generic repository pattern version for Entity Framework to the post. You don’t need to have an identity property named ID with this one.
I may regret asking this question once I know the answer:
Could you explain why the IEntity interface implemented by class Repository (code below) does not need to be implemented?
public class Repository : IRepository where T : class, IEntity
Had the code been rewritten as:
public class Repository : IEntity, IRepository where T : class
Then the compilation will complain about the ID property not being implemented.
I hope you can help.
Thanks
Robin
You need the IEntity interface only for the GetById method in the LINQ to SQL version of this generic pattern. The generic GetById() method explicitly needs all our entities to implement the IEntity interface. This is because we need them to provide us with an ID property to make our generic search for a specific Id possible.
I just added a much easier generic repository pattern for Entity Framework to the end of post and to GitHub. This ones uses DbSet, so there’s no need for the IEntity interface. For the LINQ to SQL version it still is.
Hope this helps
There’s no need for a GetById method to make this pattern work. It is only convenient when you name your identity property ID. That’s the only reason the IEntity interface is there; to give you access to the identity property in a generic way.If you use Entity Framework and have identity properties like FooId you maybe can use this ESQL workaround to get rid of the IEntity class.Found it hereNice article. Really enjoyed it !!!
Thank you Syedur
Thank you so much for explaining….
I have found this article the best among other repository tutorial i have read atleast now i have core understanding to start my demo project.
Thanks much.
Thank you Vidhya!
Very nice article. Thanks for sharing this gem.
It’s my pleasure Abdul
Hi and thanks for the great article.
I had a question,
How can we Update an Entity with DbSet ?
Hi Mohammad,
Simple call SaveChanges on the same DbContext you provide in the repository constructor.
So, the following method for update is wrong ?
[DataObjectMethod(DataObjectMethodType.Update, true)]
public TEntity Update(TEntity entity)
{
DBSet.Attach(entity);
Context.SaveChanges();
return entity;
}
Seems plausible. Why do you think it’s wrong?
Very helpful post !
1 – All Generic repository articles use only code first method to generate their model, but my case is not. I did generate the model from the database. does it affect anything ?
2 – I have built my generic repositories,but i still have a serious problem on how start testing my business logic.like in some actions I need to add entities in multiple tables and verify whether it’s made correctly by checking correctness of inserted data etc. I think it’s something related with UnitOfWork but I really want to have a clear answer on how to do things correctly like experts =)
Hi HichemC
1 – not at all. I use something like this on a legacy db, with a data centric design with LINQ to SQL on a daily basis. Works like a charm.
2 – If you find those experts, please let me know… I have some questions for them myself
It seems like you are trying to execute an integration test, but I don’t understand the problem you’re running into. Can you provide an example?
Hello and firstly nice write up of the repository and unit of work pattern implemented for NHibernate.
Decided to give this a whirl aswell and i’m running against the problem that NH 3.2 does not have a NHibernateContext class, or atleast not where i’m expecting it (Nhibernate.Linq)
And i missing something completely?
One small note by the way, why the generic repository? Why not a normal class with generic methods? So you can use one Repository object to query multiple object types.
Hey Jordon,
I have zip experience with NHibernate, so can’t help you there.
About the generic repository. I think your idea of a repository class could actually work. I’m curious why you’d prefer it that way.
I must express my deepest gratitude to you, Leon. This implementation of your was something that i was trying to do a long time ago, but never understood how to do it. Thanks for posting it.
Another thing, how would you create a Generic Factory Pattern for this Repository Pattern implementation? Assume the following: you have several types of hotels and you don’t know which one you will use in compilation time. Consider that you may know which hotel to use through an input string from client side or, i don’t know, an enumerator. Whichever may be, how would you return the correct hotel type? Considering that you have to declare it’s type when do this:
var hotelRepository = new Repository(dataContext);
Is there a way to do this?
var hotelRepository = new HotelFactoryDAL(“Vacancy Hotel”);
var allClients = hotelRepository.GetAllHotelClients();
Thanks
Hey Adriano.
Here’s my take on it. At first sight it looks like a perfect candidate for dependency injection to me. Your code has to implement some kind of generic IHotel interface. Your factory (or IoC container) takes care of the right implementation of the repository at run time, which in turn always returns your generic IHotel type. The calling code doesn’t have to know what type of hotel it receives from the repository.
Something like that? :-)
Thanks for the post. It gave me really clean picture.
This is very helpful
hi Leon
Thanks for the article
A Question :
How entity added or removed by a Repository ?
example :
public class HotelManager
{
public long Insert(Hotl hotl)
{
using (var dataContext = new HotelsDataContext())
{
var hotelRepository = new Repository(dataContext);
hotelRepository.Add(hotl);
dataContext.SaveChanges();
}
return hotl.Id;
}
}
ok or not ok ?
example :
public class HotelManager
{
public long Insert(Hotl hotl)
{
using (var dataContext = new HotelsDataContext())
{
var hotelRepository = new Repository(dataContext);
hotelRepository.Add(hotl);
dataContext.SaveChanges();
}
return hotl.Id;
}
}
Looks fine :-)
Excellent…. new things for me …
Awesome…. I did not control myself without reading all the post along with comments from readers.
I enjoyed it…Thanks Leon. I safeguarded the URL….thanks
Leon, hardstikke bedankt voor je artikel. Ik vergeet de syntax nogal eens.
I was just wondering how you would handle joins among multiple tables? Thanks
fuck you leon, youre so great for sharing this. thanx
Your introduction already explains what an ORM already does. Ayende tears in his latest presentation apart why:
http://www.youtube.com/watch?v=0tlMTJDKiug
The repository pattern is just legacy cruft.
Hi,
Great Article, But lets i have a scenarios of master child relationship to save/update and Unit Of work, then how will implement these into this pattern.
Regards,
Ravi
mcamail2002@gmail.com
I am confused about one thing. Well, I’m confused about many things, but the others are unrelated to this. I am a rookie to this design pattern, please bear with me if you can. I’ve always thought the goal would be to decouple the calling client code from direct database interraction. That would be what the Repository takes care of. But your Repository takes a datacontext object as a constructor – and thus, your client code that uses the Repository passes a datacontext object to the Repository. This seems to me that doing this still results in the client code having a direct coupling to the datasource and thus doesn’t even really need the Repository to do anything. It also means that the Repository is coupled to the calling code ‘backwards’ – it is relying on the calling client code to provide the datacontext for it to use. Why wouldn’t the repository have its own datacontext (maybe a singleton) ?
Thanks for posting the info – it is very much appreciated. I am the rookie here, and I’m just trying to find out the answers to the confusion I have.
Great Site , now i know where i am .. thanks Bookmarked
do you have more example using delegate and how its works.
Thank you for sharing this. I want to learn more about generic EF but have not found any good tutorial until now. Is this missing the SQLExpress? I’m trying to running the program but it’s missing the database.
Thanks
when i call method insert(Entity) using repository pattern with entityframework, executing fine but in adding in database , need to call savechanges method , can u guide me how to call savechanges method
That’s great and all… but what if my keys are not int? E.g. they’re Guid or ObjectId in MongoDB.
And maybe I’ve got a mix of Repos…some in Sql and some in Mongo so I can’t just change the interface. My (ASP.NET MVC) controller should NOT know how my keys are stored in data store… otherwise it’s a leaky abstraction, no?
See on StackOverflow: http://stackoverflow.com/questions/15104449/repository-pattern-how-to-be-key-type-independent
HI,
I have applied same in my application and used BLL with the same pattern, my problem is this that I want have join in multiple tables but datacontext return one table at a time and this is why All join I need to perform in presentation layer which is not practice but I applied the same, now I need to give API for mobile dev team and for this I need to use join in Business Layer which I am not able to so can you help me how I can do this. Also I want to know how I can apply Sigleton with this.
Thanks
Narendra
I have applied repository pattern and in Business layer called Repository class, but as datacontext contains one entity only and want to perform Join and which I am forced to use at presentation layer which is not a good idea can you suggest some way to have join in 2 or more table with repository pattern.
Thanks n Advance
Narendra
Leon in this generic repository what about update section?
how to implement?
thanks
Hi there,
Great post …
I am quite new to patterns.. someone was telling me about query object patterns.. any chance of you doing a tutorial on this?
Thanks
Vik