模拟DbContext.Set< T>()? [英] Mocking DbContext.Set<T>()?
问题描述
我们首先使用EF代码,并为我们的销售数据库提供数据上下文。另外,我们有一个类位于我们的数据环境之上,并进行一些基本的CRUD操作。
例如,我们有以下功能:
public static T Create< T>(int userId,T entity)其中T:class,IAllowCreate
{
if entity == null)
throw new ArgumentNullException(entity);
using(SalesContext dc = new SalesContext())
{
dc.Set< T>()
dc.SaveChanges();
返回实体;
}
}
我发现 如何创建假上下文和IDBset属性的示例。我开始实现,但是我遇到了一个问题。
我们在我们的代码中非常宽松地使用dc.Set()(如上所述),因为我们尝试创建通用CRUD方法。 ReadCustomer,ReadContact等,而不是Read()。但是,dc.Set会返回一个DbSet,而不是一个IDbSet,所以我无法模拟。有没有人能够模拟或伪造DbContext并仍然使用Set功能?
interface ISalesContext
{
IDbSet< T> GetIDbSet< T>();
}
class SalesContext:DbContext,ISalesContext
{
public IDbSet< T> GetIDbSet< T>()
{
return Set< T>();
}
}
我使用了一个不同的名字,但你可以使用 new
运算符,如果您希望隐藏常规实现。
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?
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.
这篇关于模拟DbContext.Set< T>()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!