简体   繁体   English

使用延迟加载删除具有导航属性的实体时,DbUpdateException

[英]DbUpdateException upon deleting entity with navigation properties using lazy loading

I have the following entity: 我有以下实体:

public class MyEntity
{
    public Guid? Id { get; set; }
    public string Name { get; set; }
    public virtual ApplicationUser User { get; set; }
}

And I'm trying to remove it this way: 我正在尝试通过以下方式将其删除:

var myEntity = await db.MyEntities.FindAsync(id);

if (myEntity != null)
{
    db.MyEntities.Remove(myEntity);
    await db.SaveChangesAsync();
}

And it's giving me this error: 这给了我这个错误:

An error occurred while saving entities that do not expose foreign key properties for their relationships

If I manually .Include() the navigation properties, it works fine. 如果我手动.Include()导航属性,它可以正常工作。

My question is two fold, why is Lazy Loading not loading whatever properties are necessary for this to just work, and is there a proper way to remove entities without having to manually .Include() every single navigation property beforehand? 我的问题有两个,为什么延迟加载不加载任何必需的属性才能正常工作,并且是否存在一种适当的方法来删除实体,而无需手动手动.Include()每个导航属性?

It is as I suspected, lazy loading wasn't working anymore because the dbcontext was either closed or in some closing state. 就像我怀疑的那样,由于dbcontext已关闭或处于某种关闭状态,因此延迟加载不再起作用。 I fixed all my problems by switching to a singe DbContext per request (stored in HttpContext.Current.Items) 我通过将每个请求切换到一个单一的DbContext(存储在HttpContext.Current.Items中)来解决所有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM