开发者

Mocking DbContext.Set<T>()?

We're using EF Code first, and have a data c开发者_运维知识库ontext 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜