从表(级联)中删除具有2个外键的行

时间:2015-09-11 15:04:50

标签: sql entity-framework foreign-keys cascade

我有下一个表结构:

enter image description here

RoomIdHouseId可以为空,一个字段始终为空。尝试从Houses表中删除行时,我得到了下一个异常。

  

DELETE语句与REFERENCE约束冲突   " FK_dbo.Images_dbo.Rooms_RoomId"

为什么级联删除失败?我先使用EF代码。

修改

基于@Juan Carlos的工作触发器示例:

BEGIN TRANSACTION

   delete from images 
   where houseId in ( select id from deleted )

   delete from images 
   where roomId in ( 
                       select rooms.Id
                       from rooms 
                       where rooms.HouseId in (select id from deleted)
                   )

   delete from Rooms 
   where houseId in ( select id from deleted )

   delete from houses 
   where ID in ( select ID from deleted )

COMMIT

1 个答案:

答案 0 :(得分:2)

问题是级联顺序。您遵循以下顺序:

  1. 删除房间
  2. 删除图片
  3. 删除房屋
  4. 您需要创建一个触发器来解决这个问题。现在的问题是我不知道如何使用Code First创建它。

    create trigger house_cascade
    on Houses
    instead of delete
    as
       set nocount on
       delete from rooms
       where room.id in (select i.ID 
                         from images i
                         inner join deleted d
                            on i.house_id = d.id)
    
       delete from images 
       where house_id in ( select id from deleted )
    
       delete from houses 
       where ID in ( select ID from deleted )
    

    更多信息 here

    特别是这条评论

      

    但SQL Server不支持此功能。这是晚餐很烦人,没有其他严重的数据库引擎有这个问题,人们在2005年抱怨它,Microsfot同意它在2008年是一个“理想的功能”,但仍然在2014年,他们没有它。 - Shavais于2014年8月5日21:28