HI WELCOME TO SIRIS

Implementing Repository and Unit of Work Patterns with ASP.NET MVC

In this article you will learn how to use the repository pattern for CRUD operations and how to combine it with the unit of work patterns. Before going to write the code, let's understand the repository and unit of work patterns separately.

Repository Pattern

The repository pattern is used to create an abstraction layer between the DAL (data access layer) and the BAL (business access layer) to perform CRUD operations.

Repository Pattern Implementation

The repository pattern can be implemented by using following two method :
  1. Generic Repository Pattern

    A generic repository implementation is used to define common database operations (like Create, Retrieve Update, Delete etc.) for all the database entities in a single class.
    1. public interface IRepository where TEntity : class
    2. {
    3. IEnumerable GetAll();
    4. IEnumerable Find(Expression> predicate);
    5. TEntity Get(object Id);
    6. void Add(TEntity entity);
    7. void AddRange(IEnumerable entities);
    8. void Update(TEntity entity);
    9. void Remove(object Id);
    10. void Remove(TEntity entity);
    11. void RemoveRange(IEnumerable entities);
    12. }
    13. // implementation
    14. public class Repository : IRepository where TEntity : class
    15. {
    16. protected readonly DbContext db;
    17. public Repository(DbContext _db)
    18. {
    19. db = _db;
    20. }
    21. public IEnumerable GetAll()
    22. {
    23. return db.Set().ToList();
    24. }
    25. public IEnumerable Find(Expression> predicate)
    26. {
    27. return db.Set().Where(predicate);
    28. }
    29. public TEntity Get(object Id)
    30. {
    31. return db.Set().Find(Id);
    32. }
    33. public void Add(TEntity entity)
    34. {
    35. db.Set().Add(entity);
    36. }
    37. public void AddRange(IEnumerable entities)
    38. {
    39. db.Set().AddRange(entities);
    40. }
    41. public void Remove(TEntity entity)
    42. {
    43. db.Set().Remove(entity);
    44. }
    45. public void RemoveRange(IEnumerable entities)
    46. {
    47. db.Set().RemoveRange(entities);
    48. }
    49. public void Remove(object Id)
    50. {
    51. TEntity entity = db.Set().Find(Id);
    52. this.Remove(entity);
    53. }
    54. public void Update(TEntity entity)
    55. {
    56. db.Entry(entity).State = EntityState.Modified;
    57. }
    58. }
  2. Non-Generic Repository Pattern (Specific Repository)

    A non-generic repository implementation is used to define all database operation related to an entity within a separate class. For example, if you have two entities Category and Product, each entity will have its own implementation repository.
    1. public interface IProductRepository
    2. {
    3. IEnumerable GetAll();
    4. IEnumerable Find(Expression> predicate);
    5. Product Get(int Id);
    6. void Add(Product entity);
    7. void AddRange(IEnumerable entities);
    8. void Update(Product entity);
    9. void Remove(int Id);
    10. void Remove(Product entity);
    11. void RemoveRange(IEnumerable entities);
    12. }
    13. // implementation
    14. public class ProductRepository
    15. {
    16. protected readonly DbContext db;
    17. public Repository(DbContext _db)
    18. {
    19. db = _db;
    20. }
    21. public IEnumerable GetAll()
    22. {
    23. return db.Products.ToList();
    24. }
    25. public IEnumerable Find(Expression> predicate)
    26. {
    27. return db.Products.Where(predicate);
    28. }
    29. public Product Get(int Id)
    30. {
    31. return db.Products.Find(Id);
    32. }
    33. public void Add(Product entity)
    34. {
    35. db.Products.Add(Product);
    36. }
    37. public void AddRange(IEnumerable entities)
    38. {
    39. db.Products.AddRange(entities);
    40. }
    41. public void Remove(Product entity)
    42. {
    43. db.Products.Remove(entity);
    44. }
    45. public void RemoveRange(IEnumerable entities)
    46. {
    47. db.Products.RemoveRange(entities);
    48. }
    49. public void Remove(object Id)
    50. {
    51. Product entity = db.Products.Find(Id);
    52. this.Remove(entity);
    53. }
    54. public void Update(Product entity)
    55. {
    56. db.Entry(entity).State = EntityState.Modified;
    57. }
    58. }

Recommended Repository Pattern Implementation

If you will use one of the above implementation, generic you can not use for specific operation on an entity and in case of non-generic implementation, you have to write code for common CRUD operations for each entity. So better way is, just create a generic repository for commonly used CRUD operation and for specific one create a non-generic repository and inherit form generic repository. The example code is given below:
  1. public interface IProductRepository : IRepository
  2. {
  3. IEnumerable GetProductsByCategory(int id);
  4. }
  5. public class ProductRepository : Repository, IProductRepository
  6. {
  7. public DatabaseContext context
  8. {
  9. get
  10. {
  11. return db as DatabaseContext;
  12. }
  13. }
  14. public ProductRepository(DatabaseContext _db) : base(_db)
  15. {
  16. }
  17. public IEnumerable GetProductsByCategory(int id)
  18. {
  19. return context.Products.Where(p => p.CategoryId == id).ToList();
  20. }
  21. }

Unit of work Pattern

The unit of pattern implementation manage in-memory database CRUD operations on entities as one transaction. So, if one of the operation is failing then entire db operations will be rollback.

  1. public interface IUnitOfWork : IDisposable
  2. {
  3. ICategoryRepository Categories { get; }
  4. IProductRepository Products { get; }
  5.  
  6. int SaveChanges();
  7. }
  8.  
  9. public class UnitOfWork : IUnitOfWork
  10. {
  11. private readonly DatabaseContext db;
  12.  
  13. public UnitOfWork()
  14. {
  15. db = new DatabaseContext();
  16. }
  17.  
  18. private ICategoryRepository _Categories;
  19. public ICategoryRepository Categories
  20. {
  21. get
  22. {
  23. if (this._Categories == null)
  24. {
  25. this._Categories = new CategoryRepository(db);
  26. }
  27. return this._Categories;
  28. }
  29. }
  30.  
  31. private IProductRepository _Products;
  32. public IProductRepository Products
  33. {
  34. get
  35. {
  36. if (this._Products == null)
  37. {
  38. this._Products = new ProductRepository(db);
  39. }
  40. return this._Products;
  41. }
  42. }
  43.  
  44. public int SaveChanges()
  45. {
  46. return db.SaveChanges();
  47. }
  48.  
  49. public void Dispose()
  50. {
  51. db.Dispose();
  52. }
  53. }

Entity Framework and Repository and Unit Of Work Patterns

Entity Framework is based on the repository and unit of work patterns to perform CRUD operations on an entity.

The DbSet class is based on the repository design pattern which provides us a set of method to perform CRUD operations on an entity. The DbContext class is based on unit of work pattern which includes all the DbSet entities. The DbContext class manages in-memory database operations on these entities and later saves all these updates as one transaction into database.

Advantages of Repository and Unit Of Work Design Patterns

  1. Abstract Data Access Layer and Business Access Layer from the Application.
  2. Manage in-memory database operations and later saves in-memory updates as one transaction into database.
  3. Facilitates to make the layers loosely-coupled using dependency injection.
  4. Facilitates to follow unit testing or test-driven development (TDD).
What do you think?
I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.