Entity Framework Core, deleting items from nested collection

c# entity-framework entity-framework-core

Question

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?

1
3
7/13/2018 7:40:29 PM

Accepted Answer

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();
}
6
7/15/2018 5:55:27 PM

Popular Answer

Another solution would be to declare a composite primary key InvoiceRow.Id and InvoiceRow.InvoiceId. Now it is an Identifying Relationship. As such, EF Core will indeed delete the child records when they are removed from the parent.

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

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

remove-from-collection-does-not-mark-object-as-deleted



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow