I am trying to delete an Invoice
along with any related Costs
. An Invoice
to Costs
is a 1 to many relationship.
My Snipp:
Invoice invoiceToDelete = db.Invoices.First(i => i.Id == id);
db.Invoices.Remove(invoiceToDelete);
var costs = db.Costs.Where(i => i.InvoiceId == id);
foreach (var cost in costs)
{
//Delete all related costs.
db.Costs.Remove(cost);
}
//Tried using this as well to try and delete all related costs
//db.Costs.RemoveRange(db.Costs.Where(x => x.InvoiceId == id));
db.SaveChanges();
If an Invoice
has no related Costs
, the code executes fine and the Invoice
is removed from the table.
When an Invoice
has related Costs
, however, it throws the following error:
The DELETE statement conflicted with the REFERENCE constraint "FK_Costs_Invoices". The conflict occurred in database "MyDB", table "dbo.Costs", column 'InvoiceId'.
The statement has been terminated.
Writing a delete SQL statement in SSMS, i'm able to delete from the Costs
table according to the foreign key of InvoiceId
.