从约束参考表中删除行

时间:2015-08-20 16:29:12

标签: c# entity-framework-6

我正在尝试从名为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.

参考表如下所示: enter image description here

我可以通过这种方式解决问题,但不想使用直接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从参考表中删除?

由于

1 个答案:

答案 0 :(得分:1)

最简单的方法是在约束上启用级联删除。但我认为级联被关闭是有原因的,所以我很确定你仍然必须用老式的方式做这个并删除每一个。

假设您有导航属性,它应该类似于:

foreach(var nce in prospect.NewClubEmails)
    db.NewClubProspectNewClubEmails.Remove(nce); 

db.NewClubProspects.Remove(prospect);
db.SaveChanges();