繁体   English   中英

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

[英]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.

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