我试图删除Invoice
以及任何相关Costs
。 Invoice
至Costs
是一对多关系。实体框架无法完成删除
我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();
如果Invoice
没有相关Costs
,代码执行罚款和Invoice
从表中删除。
当Invoice
有相关Costs
,但是,它引发以下错误:
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.
写作SSMS删除SQL语句,我能根据国外从Costs
表中删除钥匙InvoiceId
。
同意,除非我将它保留在实体框架中,因此丢弃的数据库将重建它与级联。看到这个SO:http://stackoverflow.com/questions/17487577/entity-framework-ef-code-first-cascade-delete-for-one-to-zero-or-one-relations – MutantNinjaCodeMonkey
非常真实,无论哪种方式完成同样的事情。这完全取决于您是否需要与数据库进行所有交互来进行级联。 –
@MutantNinjaCodeMonkey我从现有的数据库实现中首先使用代码。最好的做法是按照SO链接中描述的方式设置级联,或者是Matt的SQL本质上是做同样的事情,也许是更干净的方法? – KidBatman