从 table(级联)中删除具有 2 个外键的行
Remove row from table (cascade) that have 2 foreign keys
我有下一个table结构:
RoomId
和 HouseId
可以为空,一个字段始终为空。我在尝试从 Houses
table.
中删除行时遇到下一个异常
The DELETE statement conflicted with the REFERENCE constraint
"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
问题是级联顺序。您已遵循以下顺序:
- 删除房间
- 删除图片
- 删除房屋
你需要创建一个触发器来解决这个问题。现在的问题是我不知道如何使用 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
尤其是这条评论
But SQL Server doesn't support this. It's supper annoying, no other serious DB engine has this problem, people complained about it in 2005, Microsfot agreed that it was a "desirable feature" in 2008, but still here in 2014 they don't have it. – Shavais Aug 5 '14 at 21:28
我有下一个table结构:
RoomId
和 HouseId
可以为空,一个字段始终为空。我在尝试从 Houses
table.
The DELETE statement conflicted with the REFERENCE constraint "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
问题是级联顺序。您已遵循以下顺序:
- 删除房间
- 删除图片
- 删除房屋
你需要创建一个触发器来解决这个问题。现在的问题是我不知道如何使用 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
尤其是这条评论
But SQL Server doesn't support this. It's supper annoying, no other serious DB engine has this problem, people complained about it in 2005, Microsfot agreed that it was a "desirable feature" in 2008, but still here in 2014 they don't have it. – Shavais Aug 5 '14 at 21:28