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

entity-framework entity-framework-core

Question

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
0
4/5/2018 6:07:20 PM

Popular Answer

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);
2
4/5/2018 8:06:43 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow