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

Ole*_*rov 8 c# entity-framework 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>());
    }
Run Code Online (Sandbox Code Playgroud)

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

  public void Update(Invoice record)
  {
            dB.Invoices.Update(record);
            dB.SaveChanges();
  }
Run Code Online (Sandbox Code Playgroud)

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

Rua*_*urg 14

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

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

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

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();
}
Run Code Online (Sandbox Code Playgroud)