[英]DbContext has been disposed despite calling ToList within using statement
我看到一個操作無法完成,因為已經處理了DbContext。 即使代碼通過返回List <T>使用急切加載,也會出現異常消息。 我在EntityRepository類中有以下代碼:
public List<Entity> GetEntityByProperty(string property)
{
using (AppDbContext appDbContext = GetContext())
{
List<Entity> entities = appDbContext.Entities
.Where(e => e.Property == property)
.ToList();
return entities;
}
}
這又是從Web服務類中調用的:
private static EntityRepository EntityRepositoryStatic = new EntityRepository();
[WebMethod]
public List<Entity> GetEntityByProperty(string property)
{
return EntityRepositoryStatic.GetEntityByProperty(property);
}
EntityRepository繼承自Repository基類,該基類實現IDisposable (以處理上下文),並具有以下代碼以返回上下文的實例:
private AppDbContext appDbContext;
public AppDbContext GetContext()
{
if (appDbContext == null)
{
appDbContext = new AppDbContext();
}
return appDbContext;
}
在對存儲庫中的appDbContext進行調用的行上引發了異常。 我是否缺少明顯的東西?
這是一個龐大的遺留代碼庫,因此我們只是嘗試將對Web服務中的上下文的內聯調用替換為對存儲庫類的調用。
首次調用GetContext()
您將創建一個新上下文,然后將其返回,然后將其使用和處置。 然后,對GetContext()
的下一次調用將返回已處置的原始上下文,並且您將收到錯誤。 如果要重復使用它,則無法處理。 如果您想在處理后將其丟棄,則無法重復使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.