The Repository Pattern Example in C#

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();
            }
        }
    }
}

Repository Pattern Hotels Console

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
    }
}

86 thoughts on “The Repository Pattern Example in C#

  1. Can you provide an example to use this with EF?

    Btw, awesome blog. I really enjoy it. Found it today and bookmarked. :-)

    Jan

  2. After reading your article i realized i’m still a novice at programming :)
    Very interesting congrats! bookmarked.

    • You’re welcome Reza.
      Google should built a better translator so we all could read the poems(?) on your blog.

  3. 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.

          public interface IHotelRepository : IRepository<Hotel>
          {
              void Yadayada(Hotel hotel);
          }
       
          public class HotelRepository : IHotelRepository
          {
              public void Insert(Hotel entity)
              {
                  throw new NotImplementedException();
              }
       
              public void Delete(Hotel entity)
              {
                  throw new NotImplementedException();
              }
       
              public IQueryable<Hotel> SearchFor(Expression<Func<Hotel, bool>> predicate)
              {
                  throw new NotImplementedException();
              }
       
              public IQueryable<Hotel> GetAll()
              {
                  throw new NotImplementedException();
              }
       
              public Hotel GetById(int id)
              {
                  throw new NotImplementedException();
              }
       
              public void Yadayada(Hotel hotel)
              {
                  throw new NotImplementedException();
              }
          }
  4. 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?

      • Thanks for the article. I tried to build my own repository and i was successful. Your article was great reference. But i am stuck at one point.

        I am trying to implement repository pattern with legacy code. This code uses lots of stored procedures. Now i am stuck and can’t figure out how to call stored procedure with repository pattern.

        Shall i use DataContext directly to call stored procedures?
        or is there some other way with repository pattern.

        I would really appreciate. Looking forward to hear from you.
        Thanks.

      • I tried something like following.
        There is a person entity. I want to get the person detail. Person detail consists of fields from Person table and fields from Address table. I called a stored procedure named uspGetPersonDetail to get the detail. So i created a PersonRepository for entity specific operation like following.

        public interface IPersonRepository
        {
        uspGetPersonDetailResult GetPersonDetail(int personID);
        }

        public class PersonRepository : Repository, IPersonRepository
        {
        public PersonRepository(RepositoryPatternDataContext context)
        : base(context)
        {

        }

        public uspGetPersonDetailResult GetPersonDetail(int personID)
        {
        return _context.uspGetPersonDetail(personID).SingleOrDefault();
        }
        }

        Is this correct or am i not understanding the principle of repository pattern?
        If this correct, i have a question.

        uspGetPersonDetail stored procedure selects data from Person and Address table. I am using this stored procedure in Person repository. I could have used this sp in Address repository. Is it ok to use this stored procedure in Person repository?

  5. 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.

  6. 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!

  7. 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.

  8. 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 8)

      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 here

  9. 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.

      • So, the following method for update is wrong ?
        [DataObjectMethod(DataObjectMethodType.Update, true)]
        public TEntity Update(TEntity entity)
        {
        DBSet.Attach(entity);
        Context.SaveChanges();
        return entity;
        }

  10. 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 :mrgreen:

      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?

  11. 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. :mrgreen:

      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.

  12. 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? :-)

  13. 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;
      }
      }

  14. 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

  15. 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.

    • I saw that also. You are correct, the client code is supposed to be ignorant on how the repository handle the data’s persistence. The repository should be abstracted enough that the client does not know or care whether the data is from a database, XML, web service, or just text file.

  16. 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

  17. 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

  18. 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

  19. 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

  20. 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

    • Repo returns w/e tech you are using. If you are using EF then your nav methods should be abvailable in the returned entity by the GetXx or Searchxxx methods. If not consider hydrating your ORM with DTOs

  21. 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

  22. Excellent. Came here from Stackoverflow. It helped me to understand generic repository pattern. Now I won’t have to create 100′s of repository classes.

    Can you update it with Unit of work pattern ?

  23. public class RepositoryDepartment : Repository, IRepositoryDepartment

    How would you apply DI in respect to your repository pattern.
    For example, take a look at the RepositoryDepartment class, where Repository implements your IRepository

    If i resolve either to IRepository or IRepositoryDepartment, I get only the half functionality of RepositoryDepartment. If I had a single interface, this would not be a problem.

    The problem is, that I can only resolve a type mapped to one interface.

  24. I’m coming to the party a bit late, but I really like the design you write about. But there is something that doesn’t sit quite right with me, and it has to do with the DataContext (or any database connection mechanism)…

    I’ve implemented something like this, except I have a Pool of connections that is stored in Global Cache (in an Asp.net application). The reason I’ve resorted to “global data” is because I just don’t like the idea of taking a DataContext object in the constructor of *any* object. It just seems cleaner to stick it in the global cache, even though I understand global data isn’t optimal either.

    Have you pondered that issue, or do you think it’s a moot point? Certainly, it isn’t unreasonable that a database-using class should take a database connection mechanism in the constructor, but it doesn’t seem very elegant…Am I just overthinking this?

  25. ThankYou so much for this post! I’ve been scavanging the web far and wide for something half as clear as this! I would deeply appreciate this even more eith the new WCF Transaction services (wink wink) ;)

    I do concur that you can make your repo more flexible with type agnostic:
    IRepo where T : class, IQueryable, IEntity where ID : struct or class

  26. Hello,
    I am new to this pattern and database. How do I run your sample code using your database? I get error I’m not able to access your database when I run the sample code.

    Thanks.

  27. Just wanted to leave a thank you. Your example has really helped me in my internship. I’m not sure if my work is perfect, but right now everything seems to come along just fine. Though I’m still working out the right way to execute Lambda expressions, not sure how to do proper joins on here. Got some ideas, so going by the good old trail and error.
    Many thanks again!

    Greetings o7

  28. Hi,

    I was just wondering why we would need a IEntity in the Linq-to-sql example and not in the EF one? The EF also requires an ID for its Find function? Confused

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>