问题描述
跟随我的其他的问题,我有另一个问题关于嘲笑EF Code First。
我现在有一个我的更新方法,如下所示:
if(entity == null)
throw new ArgumentNullException(entity);
Context.GetIDbSet< T>()。Attach(entity);
Context.Entry(entity).State = EntityState.Modified;
Context.CommitChanges();
返回实体;
上下文是我自己的DbContext的界面。
我正在运行的问题是,如何处理
Context.Entry(entity).State
。
我已经走过这段代码,当我有一个真正的DbContext作为我的Context界面的实现时,它可以工作。但是当我把假的上下文放在那里时,我不知道如何处理它。
DbEntityEntry类没有构造函数,所以我不能只创建在我的假场景中有一个新的。
有没有人在您的CodeFirst解决方案中嘲笑或伪造DbEntityEntry吗?
$ b $或者有更好的方式来处理状态变化?
就像其他情况一样,你需要什么是添加一个额外的间接级别:
接口ISalesContext
{
IDbSet< T> GetIDbSet< T>();
void SetModified(object entity)
}
class SalesContext:DbContext,ISalesContext
{
public IDbSet< T> GetIDbSet< T>()
{
return Set< T>();
}
public void SetModified(object entity)
{
条目(实体).State = EntityState.Modified;
}
}
所以,而不是调用实现,你只需调用 SetModified
。
Following on the heels of my other question about mocking DbContext.Set I've got another question about mocking EF Code First.
I now have a method for my update that looks like:
if (entity == null)
throw new ArgumentNullException("entity");
Context.GetIDbSet<T>().Attach(entity);
Context.Entry(entity).State = EntityState.Modified;
Context.CommitChanges();
return entity;
Context is an interface of my own DbContext.
The problem I'm running in to is, how do I handle the
Context.Entry(entity).State
.
I've stepped through this code and it works when I have a real live DbContext as the implementation of my Context interface. But when I put my fake context there, I don't know how to handle it.
There is no constructor for a DbEntityEntry class, so I can't just create a new one in my fake context.
Has anyone had any success with either mocking or faking DbEntityEntry in your CodeFirst solutions?
Or is there a better way to handle the state changes?
Just like the other case, what you need is to add an additional level of indirection:
interface ISalesContext
{
IDbSet<T> GetIDbSet<T>();
void SetModified(object entity)
}
class SalesContext : DbContext, ISalesContext
{
public IDbSet<T> GetIDbSet<T>()
{
return Set<T>();
}
public void SetModified(object entity)
{
Entry(entity).State = EntityState.Modified;
}
}
So, instead of calling the implementation, you just call SetModified
.
这篇关于模拟或伪造DbEntityEntry或创建一个新的DbEntityEntry的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!