Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking DbContext.Set<T>()?

We're using EF Code first, and have a data context for our sales database. Additionally, we have a class that sits on top of our data context and does some basic CRUD operations.

For example, we have the following function:

public static T Create<T>(int userId, T entity) where T : class, IAllowCreate
{
    if (entity == null)
        throw new ArgumentNullException("entity");

    using (SalesContext dc = new SalesContext())
    {
         dc.Set<T>().Add(entity);
         dc.SaveChanges();

         return entity;
    }
}

I found an example of how to create fake contexts and IDBset properties. I started implementing that, but I ran in to an issue.

We use dc.Set() quite liberally (as seen above) in our code, as we attempt to create generic CRUD methods. Instead of having a ReadCustomer, ReadContact etc, we would just do Read(). However, dc.Set returns a DbSet, not an IDbSet, so I'm not able to mock that.

Has anyone been able to mock or fake DbContext and still use the Set functionality?

like image 437
taylonr Avatar asked Feb 15 '11 17:02

taylonr


1 Answers

interface ISalesContext
{
    IDbSet<T> GetIDbSet<T>();
}

class SalesContext : DbContext, ISalesContext
{
    public IDbSet<T> GetIDbSet<T>()
    {
        return Set<T>();
    }
}

I used a different name, but you can use the new operator if you prefer to hide the regular implementation.

like image 138
Diego Mijelshon Avatar answered Feb 02 '23 04:02

Diego Mijelshon