Click here to Skip to main content
13,899,965 members
Click here to Skip to main content
Add your own
alternative version


26 bookmarked
Posted 21 Apr 2018
Licenced CPOL

Very Thin Database Layer using UnitOfWork Pattern and EntityFramework

, 27 Apr 2018
Rate this:
Please Sign up or sign in to vote.
Building very thin database layer when using unit of work pattern together with Enityframework


I have been involved in many projects during my time as a software developer and have seen different ways of accessing databases using different patterns, sometimes too much code when the same things could be done with much less code.

One thing we developers should be aware of when using EntityFramework is that DB Context is "HOLY" and should be handled with care. Create one just before you need it and Dispose it right after you are done with it.

DO NOT share it with different threads or keeping it alive during the whole time your application instance life-cycle, you may end up getting memory leaks.

Below, you will find implementation for UnitOfWork pattern using EntityFramework and DContext.


If you are using Service/Repository pattern and want to want to build a thin Repository using unit of work pattern, this should get you on the right track.

I have seen different ways exposing data from the repository, sometimes returning IQueryable directly from repository, I don't recommend this way for 3 reasons:

  1. It is harder to mock when you need to write tests.
  2. Every time you read data from database, you need to convert it to CLR type using ToList() method.
  3. Composing Query can affect performance (Read this link from MIcrosoft)

Using the Code

This time, we are going to build a simple repository. Many think that everything that handles data has to be done through repository (I have seen a project that accesses a web service using repository), I think that Repository should only handle queries against database.

Below are interfaces and classes for setting up Unit of work pattern using EntityFramework.

This interface defines the Repository:

public interface IGenericRepository
    Task<IEnumerable<T>> FindAsync<T>(Expression<Func<T, bool>> expression) where T : class;
    Task<T> SingleOrDefaultAsync<T>(Expression<Func<T, bool>> expression) where T : class;
    void Add<T>(T entity) where T : class;
    void Update<T>(T entity) where T : class;
    void Delete<T>(T entity) where T : class;

This class implements IGenericRepository:

public class GenericRepository : IGenericRepository
       private readonly IDatabaseContext _dbContext;

       public GenericRepository(IDatabaseContext dbContext)
           _dbContext = dbContext;

       public async Task<IEnumerable<T>> FindAsync<T>
       (Expression<Func<T, bool>> expression) where T : class
           return await _dbContext.Set<T>().Where(expression).ToListAsync();

       public async Task<T> SingleOrDefaultAsync<T>
       (Expression<Func<T, bool>> expression) where T : class
           return await _dbContext.Set<T>().SingleOrDefaultAsync(expression);

       public void Add<T>(T entity) where T : class

       public void Update<T>(T entity) where T : class
           _dbContext.Entry(entity).State = EntityState.Modified;

       public void Delete<T>(T entity) where T : class

Unit of Work

Using unit of work pattern will help you make several changes to your database model and commit all at once, doing so will help you make sure that all changes have been saved properly or in other case, you can rollback.

Defining unit of work interface:

public interface IUnitOfWork : IDisposable
    IGenericRepository Repository();
    Task CommitAsync();

Class that implements IUnitOfWork, you can see that I use one DB Context per UnitOfWork instance.

public class UnitOfWork : IUnitOfWork
    private readonly IDatabaseContext _databaseContext;

    public UnitOfWork(IDatabaseContext databaseContext)
        _databaseContext = databaseContext;

    public IGenericRepository Repository()
        return new GenericRepository(_databaseContext);

    public void Dispose()

    public Task CommitAsync()
        return _databaseContext.SaveChangesAsync();

For creating a new DB Context every time we need one, I recommend using a Factory pattern.

public interface IUnitOfWorkFactory
    IUnitOfWork Create();

Implementing IUnitOfWorkFactory:

public class UnitOfWorkFactory : IUnitOfWorkFactory
    public IUnitOfWork Create()
        return new UnitOfWork(new DatabaseContext());

Recommended, define interface for exposing properties from DB Context:

public interface IDatabaseContext : IDisposable
    DbEntityEntry Entry(object entity);
    DbSet<TEntity> Set<TEntity>() where TEntity : class;
    DbSet Set(System.Type entityType);
    int SaveChanges();
    Task<int> SaveChangesAsync();
    Task<int> SaveChangesAsync(CancellationToken cancellationToken);
public class DatabaseContext : DbContext, IDatabaseContext
    public DatabaseContext() : base("OrganizationDb")

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
        // Add your model configuration here

Now, we are able to access database using our DB models for reading data.

Below, you'll find a service as example.

public interface IPersonService
    Task<List<PersonDto>> GetPersonsAsync(string term);
public class PersonService : IPersonService
    private readonly IUnitOfWorkFactory _unitOfWorkFactory;

    public PersonService(IUnitOfWorkFactory unitOfWorkFactory)
        _unitOfWorkFactory = unitOfWorkFactory;
    public async Task<List<PersonDto>> GetPersonsAsync(string term)
        using (var unitOfWork = _unitOfWorkFactory.Create())
            var persons = await unitOfWork.Repository().FindAsync<Person>
                          (x => x.Name.Contains(term));
            return persons.Select(person => new PersonDto(person.Name)).ToList();

This is just a simple example, you can always extend repository implementation, or configure your IoC to call Dispose after every request. Sky is the limit :)

Happy coding!


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Burim Hajrizaj
Software Developer (Senior) Trigonit AB
Sweden Sweden
Developer with broad skills set and architecture awareness with more than 20 years’ experience in design and development of client/server, web based and n-tier applications. Extensive experience on windows applications as well as web applications, windows services, web services and similar

You may also be interested in...


Comments and Discussions

QuestionSaveChangesAsync Pin
Agha.net26-Apr-18 15:38
memberAgha.net26-Apr-18 15:38 
AnswerRe: SaveChangesAsync Pin
Burim Hajrizaj27-Apr-18 2:53
memberBurim Hajrizaj27-Apr-18 2:53 
PraiseMy Vote of 5 Pin
Ross McNichol26-Apr-18 13:26
memberRoss McNichol26-Apr-18 13:26 
GeneralRe: My Vote of 5 Pin
Burim Hajrizaj27-Apr-18 2:52
memberBurim Hajrizaj27-Apr-18 2:52 
GeneralMy vote of 5 Pin
Hyland Computer Systems26-Apr-18 5:50
memberHyland Computer Systems26-Apr-18 5:50 
GeneralRe: My vote of 5 Pin
Burim Hajrizaj27-Apr-18 2:55
memberBurim Hajrizaj27-Apr-18 2:55 
GeneralMy vote of 4 Pin
raddevus21-Apr-18 9:27
mvaraddevus21-Apr-18 9:27 
GeneralRe: My vote of 4 Pin
Burim Hajrizaj22-Apr-18 22:15
memberBurim Hajrizaj22-Apr-18 22:15 
GeneralRAR file corrupt Pin
Henk Meijerink25-Apr-18 16:03
memberHenk Meijerink25-Apr-18 16:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04 | 2.8.190306.1 | Last Updated 27 Apr 2018
Article Copyright 2018 by Burim Hajrizaj
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid