实体框架核心级联删除一对多关系 [英] Entity Framework Core cascade delete one to many relationship
问题描述
public class Station : IEntitie
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public virtual ICollection<RegulatorySchedule> RegulatoryScheduleDispatchStations { get; set; }
public virtual ICollection<RegulatorySchedule> RegulatoryScheduleDestinationStations { get; set; }
}
public class RegulatorySchedule : IEntitie
{
[Key]
public int Id { get; set; }
public virtual Station DispatchStation { get; set; }
public virtual Station DestinationStation { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<RegulatorySchedule>()
.HasOne(s => s.DestinationStation)
.WithMany(s => s.RegulatoryScheduleDestinationStations)
.OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict);
modelBuilder.Entity<RegulatorySchedule>()
.HasOne(s => s.DispatchStation)
.WithMany(s => s.RegulatoryScheduleDispatchStations)
.OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict);
}
只有在删除限制
。
OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict)
否则,它将引发异常:
The database is created during migration only when I clearly expose the behavior when deleting Restrict
OnDelete (Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict)
.
Otherwise, it throws an exception:
在表$ b $上引入FOREIGN KEY约束
'FK_RegulatorySchedules_Stations_DispatchStationId' b'RegulatorySchedules'可能会导致循环或多个级联路径。
指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他
FOREIGN KEY约束。
"Introducing FOREIGN KEY constraint 'FK_RegulatorySchedules_Stations_DispatchStationId' on table 'RegulatorySchedules' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints."
我需要删除表的Station Station和与表相关的属性RegulatorySchedules DispatchStation和DestinationStation暴露为NULL。
但是Restrict选项在删除无法放下的SetNull时会有例外。
告诉我怎么做?
I need the removal of the Station Stations of the table and the table-related properties RegulatorySchedules DispatchStation and DestinationStation exposed to NULL. But Restrict option there is an exception when you delete a SetNull I can not put. Tell me how to be?
推荐答案
描述的问题与实体框架无关-这是对MS SQL Server本身。具有多个FK的表可能只有其中一个具有 cascade 删除。
Described "problem" is not related to Entity Framework - this is restriction of MS SQL Server itself. Table with several FKs may have only one of them with cascade delete.
因此,一旦您需要两个FK都具有级联-您应该在代码中实现此类清理。将一个(或两个)FK设置为 DeleteBehavior.Restrict
,并在控制器/服务中,然后手动删除 Station
并删除所有相关的 RegulatorySchedule
So, as soon as you need both FKs to have cascade - you should implement such "cleanup" in your code. Set one (or both) FKs to DeleteBehavior.Restrict
, and in your controller/service prior to removing Station
manually find and delete all related RegulatorySchedule
这篇关于实体框架核心级联删除一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!