我正在尝试从名为NewClubProspectNewClubEmail的表中具有引用行的表(NewClubProspect)中删除对象
我得到的错误是
The DELETE statement conflicted with the
REFERENCE constrain
"FK_dbo.NewClubProspectNewClubEmail_dbo.NewClubProspect_NewClubProspect_Id"
The conflict occurred in database
"Reporting", table "dbo.NewClubProspectNewClubEmail", column 'NewClubProspect_Id'.
The statement has been terminated.
我可以通过这种方式解决问题,但不想使用直接SQL。为简洁起见,我删除了try / catches:
//Delete out of the reference table first
var sql = "delete from NewClubProspectNewClubEmail where NewClubProspect_Id = @p0";
var r = ReportingDBTasks.Query(sql,prospect.Id);
//Delete the parent object
db.NewClubProspects.Remove(prospect);
db.SaveChanges();
如何使用EF而不是直接SQL从参考表中删除?
由于
答案 0 :(得分:1)
最简单的方法是在约束上启用级联删除。但我认为级联被关闭是有原因的,所以我很确定你仍然必须用老式的方式做这个并删除每一个。
假设您有导航属性,它应该类似于:
foreach(var nce in prospect.NewClubEmails)
db.NewClubProspectNewClubEmails.Remove(nce);
db.NewClubProspects.Remove(prospect);
db.SaveChanges();