是否可以on update cascade
使用触发器来实现?我编写了以下示例代码(也在http://sqlfiddle.com/#!6/d7298/1上):
create table Parent
(
Id int not null,
IsDeleted bit not null,
)
alter table Parent add constraint PPK primary key (Id, IsDeleted)
create table Child
(
Id int not null,
IsDeleted bit not null,
ParentId int not null,
ParentIsDeleted bit not null,
)
alter table Child add constraint CPK primary key (Id, IsDeleted)
alter table Child add constraint CFK foreign key (ParentId, ParentIsDeleted) references Parent(Id, IsDeleted)
go
create trigger ParentAfterUpdate on Parent
after update
as
begin
if update(IsDeleted)
update c set c.ParentIsDeleted = i.IsDeleted from Child c inner join Inserted i on c.ParentId = i.Id
end
go
insert into Parent values(100,0)
insert into Child values(1000,0,100,0)
update Parent set IsDeleted = 1
这不起作用,因为CFK
约束会引发错误。我希望级联软删除,以便在软删除父记录时软删除子记录。
IsDeleted
取出CFK
可以让我将更新级联到Child
,但在高度并发的环境中,我相信应该有可能以损坏的数据库状态结束:
在 T0:实体框架将父级加载到内存中。没有删除父级。
在 T1:父级被另一个独立查询软删除
在 T2:EF 插入一条子记录,但由于IsDeleted
不是外键的一部分,因此有一个活动子记录指向已删除的父记录。