简体   繁体   中英

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.

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?

It is as I suspected, lazy loading wasn't working anymore because the dbcontext was either closed or in some closing state. I fixed all my problems by switching to a singe DbContext per request (stored in HttpContext.Current.Items)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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