Entity Framework Core,从嵌套集合中删除项目 [英] Entity Framework Core, deleting items from nested collection

查看:25
本文介绍了Entity Framework Core,从嵌套集合中删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个班

 public class InvoiceRow
    {
        public int Id { get; set; }
        public int InvoiceId { get; set; }

        public int ProductId { get; set; }
        public virtual Product Product { get; set; }

        public int Amount { get; set; }
    }



   public class Invoice
    {
            public int Id { get; set; }
            private ICollection<InvoiceRow> _rows;
            public virtual ICollection<InvoiceRow> Rows => _rows ?? (_rows = new List<InvoiceRow>());
    }

我在存储库类中使用 Update 方法

I use Update method in the repository class

  public void Update(Invoice record)
  {
            dB.Invoices.Update(record);
            dB.SaveChanges();
  }

它适用于更新行集合中的值并添加新行,但是它不会删除项目,如果我传递的对象行数少于数据库中的行数.最好的方法是什么?

It works for updating values in the collection of rows and adding new rows as well, however it doesn't remove items, if I pass object with less rows than it has in the database. What is the best approach to do it?

推荐答案

那是因为数据库中的行没有被标记为删除.

That is because the rows in the database are not marked for deletion.

仅更新新的或更改的项目.集合中丢失"的项目不被视为被删除.

Only new or changed items are updated. 'Missing' items from a collection are not considered to be deleted.

所以您需要做的是自己标记要删除的项目.像这样:

So what you'll need to do is mark the items for deletion yourself. Something like this:

public void Update(Invoice record)
{
    var missingRows = dB.InvoiceRows.Where(i => i.InvoiceId == record.Id)
                        .Except(record.Rows);
    dB.InvoiceRows.RemoveRange(missingRows);

    dB.Invoices.Update(record);
    dB.SaveChanges();
}

这篇关于Entity Framework Core,从嵌套集合中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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