我試圖做以相同的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