使用EF Core保存附加实体时如何删除子实体 [英] How to remove child entities when saving attached entity with EF Core

查看:211
本文介绍了使用EF Core保存附加实体时如何删除子实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用EF Core的存储库。在以下情况下,我首先获取一个实体以及相关的子集合。然后,我删除所有子项,添加一个新的子项,并同时更新父实体的一个属性。

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.

我如何获得EF来跟踪已删除的已删除子实体?

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);


推荐答案

呼叫

db.Children.RemoveRange(parent.Children);

应从数据库中删除子实体。

should remove the child entities from the database.

在存储库中添加方法:

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

并使用它:

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

这篇关于使用EF Core保存附加实体时如何删除子实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆