Jason Mitchell

Data Access Using a Generic Repository in C#

The repository pattern is an abstraction layer which provides a well-organised approach to maintaining a separation between an applications data access and business logic layers.  This gives us the important advantages of making code more maintainable and readable and improving the testability of our code.  It also works great with dependency injection!

When I started looking at the repository pattern I found that a lot of the samples on the internet used explicitly typed repositories such as ICustomerRepository and IOrderRepository.  However for a website I’m currently working on all of my CRUD operations were pretty much the same and I wanted to reduce the amount of code I needed to write so I implemented a basic generic repository which would work with any of my data model classes.

The following code snippet  is the interface for the basic repository I’ve been using:

public interface IRepository
{
    void Save();
 
    IQueryable Query(Expression<Func<T, bool>> filter = null) where T : class;
    T SingleOrDefault(Expression<Func<T, bool>> predicate) where T : class;
    void Insert(T entity) where T : class;
    void Update(T entity) where T : class;
    void Delete(T entity) where T : class;
}

This interface only defines the most basic data access operations and should probably be expanded on to provide support for beginning, committing and rolling back transactions.

The following class is an implementation of IRepository which has been implemented to abstract access to an Entity Framework Code First data context:

public class EntityFrameworkRepository : IRepository
{
    private readonly SiteDataContext dataContext;
 
    public EntityFrameworkRepository(SiteDataContext dataContext)
    {
        this.dataContext = dataContext;
    }
 
    public void Save()
    {
        dataContext.SaveChanges();
    }
 
    public IQueryable Query(Expression<Func<T, bool>> filter = null) where T : class
    {
        IQueryable query = dataContext.Set();
 
        if (filter != null)
            query = query.Where(filter);
 
        return query;
    }
 
    public T SingleOrDefault(Expression<Func<T, bool>> predicate) where T : class
    {
        return dataContext.Set().SingleOrDefault(predicate);
    }
 
    public void Insert(T entity) where T : class
    {
        dataContext.Set().Add(entity);
    }
 
    public void Update(T entity) where T : class
    {
        DbEntityEntry entityEntry = dataContext.Entry(entity);
        if(entityEntry.State == EntityState.Detached)
        {
            dataContext.Set().Attach(entity);
            entityEntry.State = EntityState.Modified;
        }
    }
 
    public void Delete(T entity) where T : class
    {
        dataContext.Set().Remove(entity);
    }
}

There’s nothing particularly complicated about this class so  I’m just going to give a quick example on how to use it and leave it at that!  If you have the following class defined in an Entity Framework Code First data context:

public class Customer
{
    [Key]
    public int ID { get; set; }
 
    [Required]
    public string FirstName { get; set; }
 
    [Required]
    public string LastName { get; set; }
}

You could query your customer data really easily using a LINQ expression:

var customers = from c in repository.Query()
                where c.FirstName == "Jason"
                select c;

or a lambda expression:

var customer = repository.Query(c => c.FirstName == "Jason");

For more information about the repository pattern see: http://msdn.microsoft.com/en-us/library/ff649690.aspx

No related posts.


Categorised as: Uncategorized


2 Comments

  1. James Hinson says:

    I stumbled accross your blog today looking at different peoples ideas on particle engines. I am a self educated software and programing tech which means I have many limitations. I can see you don’t get many comments. Just wanted to say I enjoyed reading your posts.

    • Jason says:

      Yeah it’s pretty quiet around here. I really appreciate your feedback!

      Particles engines are something I really enjoy working with although I haven’t done much with them recently.

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> <pre lang="" line="" escaped="" highlight="">

Spam protection by WP Captcha-Free