简体   繁体   English

Entity Framework Core,从嵌套集合中删除项目

[英]Entity Framework Core, deleting items from nested collection

I have two classes我有两节课

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

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

Another solution would be to declare a composite primary key InvoiceRow.Id and InvoiceRow.InvoiceId .另一种解决方案是声明一个复合主键InvoiceRow.IdInvoiceRow.InvoiceId Now it is an Identifying Relationship .现在它是一个识别关系 As such, EF Core will indeed delete the child records when they are removed from the parent.因此,当子记录从父记录中删除时,EF Core 确实会删除它们。

https://stackoverflow.com/a/17726414/7718171 https://stackoverflow.com/a/17726414/7718171

https://stackoverflow.com/a/762994/7718171 https://stackoverflow.com/a/762994/7718171

remove-from-collection-does-not-mark-object-as-deleted 从集合中删除不将对象标记为已删除

I'm using Entity Framework Core 6 and the following code works for me.我正在使用 Entity Framework Core 6,以下代码适用于我。

public void Update(Invoice invoice)
{

        //1. valid invoice rows ids
        var validInvoiceRowIds = invoice.InvoiceRows.Select(ir => ir.Id).ToList();

        //2. missing invoice rows
        var missItems = _context.InvoiceRows
            .Where(ir => ir.InvoiceId == invoice.Id && !validInvoiceRowIds.Contains(ir.Id))
            .ToList();

        _context.RemoveRange(missItems);

        _context.Update(entity);
        _context.SaveChanges();

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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