[英]DbUpdateException upon deleting entity with navigation properties using lazy loading
我有以下實體:
public class MyEntity
{
public Guid? Id { get; set; }
public string Name { get; set; }
public virtual ApplicationUser User { get; set; }
}
我正在嘗試通過以下方式將其刪除:
var myEntity = await db.MyEntities.FindAsync(id);
if (myEntity != null)
{
db.MyEntities.Remove(myEntity);
await db.SaveChangesAsync();
}
這給了我這個錯誤:
An error occurred while saving entities that do not expose foreign key properties for their relationships
如果我手動.Include()
導航屬性,它可以正常工作。
我的問題有兩個,為什么延遲加載不加載任何必需的屬性才能正常工作,並且是否存在一種適當的方法來刪除實體,而無需手動手動.Include()
每個導航屬性?
就像我懷疑的那樣,由於dbcontext已關閉或處於某種關閉狀態,因此延遲加載不再起作用。 我通過將每個請求切換到一個單一的DbContext(存儲在HttpContext.Current.Items中)來解決所有問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.