Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good idea to wrap my DbContext in a Unit of Work class?

I am trying to implement Unit of Work/Repository pattern in my MVC Web application.

Since DbContext itself is a unit of work, I want to mix it with my own UOW for testing and decoupling purposes (decoupling business layer from EF). Is it then a good idea to just wrap my DbContext inside an UOW class like the following?

Example:

Code reduced for clarity

public interface IUnitOfWork
{
    void Save();
}

public MyContext : DbContext
{
    // DbSets here
}

public UnitOfWork : IUnitOfWork
{
    public MyContext myContext { get; set; }

    void Save()
    {
        myContext.SaveChanges();
    }
}

Then I would call UnitOfWork instance to perform data operations.

Thanks a lot in advance :-)

like image 538
Kamran Avatar asked Aug 12 '13 11:08

Kamran


1 Answers

I depends on what you are trying to accomplish.

I you want to create an abstraction layer between Entity Framework and your business logic, then yes, it's a good idea. But then you have to do a complete abstraction meaning that your repository classes can not expose IQueryable<T>.

If you don't create a complete abstraction, then I do not see any reason to wrap the DbContext in a unit of work class.

like image 147
jgauffin Avatar answered Oct 14 '22 01:10

jgauffin