我试图做以相同的DbContext第二个电话会导致错误“的DbContext已配置”
public void SomeTestMethod(){
var person = this.PersonManager.Get(new Guid("someguid"));
person.Lastname = "Jameson";
this.PersonManager.Save(person); // This goes wrong
}
如果它出错
上述保存方法调用的代码:
protected void Add<T>(T source, MyEntities context, bool isNew) where T : class
{
if (isNew)
{
context.Set<T>().Add(source);
}
else
{
var entry = context.Entry(source);
if (entry.State == EntityState.Detached)
{
context.Set<T>().Attach(source);
entry.State = EntityState.Modified;
}
}
}
var entry = context.Entry(source);
行是导致此错误的行:
The operation cannot be completed because the DbContext has been disposed.
我见过的回答到,建议使用.ToList()(或别的东西来执行的链接)类似的问题,但是这已经发生了,因为Get
返回一个DTO对象。
一些背景
的PersonManager
在保存时,使用此设置的DbContext:
var context = new MyEntities();
this.PersonRepository = repositoryProvider.GetRepositoryByType<PersonRepository>(context);
的var context = new MyEntities();
只是为了得到它现在的工作,这将是DI注入。
而这又取决于这一点:
public T GetRepositoryByType<T>(MyEntities context) where T : IContextDependent
{
var instance = this.Repositories.SingleOrDefault(x => x is T);
instance.SetContext(context);
return (T)instance;
}
由于使用了相同的PersonManager
,事实上同PersonRepository
用于(并因此同样的情况下),所以不看看它为什么会在第二次电话中处理。
你的Get和Save都使用'PersonRepository'吗? –
@AlexanderDerck:正确,由运行它们的'PersonManager'提供。 – Spikee