首页 > 解决方案 > 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>());
    }

我在存储库类中使用更新方法

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

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

标签: c#entity-frameworkentity-framework-core

解决方案


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

仅更新新的或更改的项目。集合中的“缺失”项目不被视为已删除。

因此,您需要自己标记要删除的项目。像这样的东西:

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

推荐阅读