我有下一个表结构:
RoomId
和HouseId
可以为空,一个字段始终为空。尝试从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
答案 0 :(得分:2)
问题是级联顺序。您遵循以下顺序:
您需要创建一个触发器来解决这个问题。现在的问题是我不知道如何使用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