How to remove child entities when saving attached entity with EF Core

て烟熏妆下的殇ゞ 提交于 2019-12-11 22:59:56

问题


I have a Repository using EF Core. In the below scenario I first fetch an entity along with a related child collection. I then remove all the children and add a new child and also update one property on the parent entity.

After saving the property on the parent is update, the new child entity is added but all the original child entities are still in the database.

How can I get EF to track the removed child entities as deleted?

class Repository
{
    public Parent GetParent(int id)
    {
        using (var db = new LocalDbContext())
        {
            return db.Parents.Include(item => item.Images).FirstOrDefault(item => item.Id == id);
        }
    }

    public void UpdateParent(Parent parent)
    {
        using (var db = new LocalDbContext())
        {
            var entry = db.Parents.Attach(parent);
            entry.State = EntityState.Modified;
            db.SaveChanges();
        }
    }
}


var instance = new LocalDbContext();
var repository = new Repository();
var parent = repository.GetParent(123);
parent.SomeField = 999;
parent.Children.RemoveRange(0, parent.Children.Count);
parent.Children.Add(new Child() { SomeOtherField = "qwe" });
repository.UpdateParent(parent);

回答1:


Calling

db.Children.RemoveRange(parent.Children);

should remove the child entities from the database.

Add a method in repository:

public void RemoveChildren(IEnumerable<Children> children)
{
   using(var db = new LocalDbContext())
   {
       db.Children.RemoveRange(children);
       db.SaveChanges();
   }
}

And use it:

var parent = repository.GetParent(123);
repository.RemoveChildren(parent.Children);


来源:https://stackoverflow.com/questions/49678791/how-to-remove-child-entities-when-saving-attached-entity-with-ef-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!