You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EF Core执行Add migration、update database出现多cascade path错误如何解决

问题根因

这个报错是SQL Server本身的级联路径限制触发的,与EF Core的配置映射有关:
同一个PatientFile表存在3个外键同时指向Physiotherapist表,SQL Server会判定存在多个潜在的级联删除路径。即便你显式配置了DeleteBehavior.Restrict,部分版本的EF Core在生成迁移时,仍可能将Restrict映射为SQL Server可识别的约束时出现偏差,触发数据库层面的校验报错。

解决方案

按照以下步骤操作即可解决:

  • 第一步:删除项目Migrations文件夹下所有历史迁移文件,彻底清除旧配置残留
  • 第二步:修改OnModelCreating中三个指向物理治疗师的外键的删除行为,将DeleteBehavior.Restrict替换为DeleteBehavior.NoAction,修改后的配置如下:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Patient>()
    .HasOne(p => p.PatientFile)
    .WithOne(pf => pf.Patient)
    .HasForeignKey<PatientFile>(p => p.PatientId)
    .OnDelete(DeleteBehavior.Restrict);

    modelBuilder.Entity<PatientFile>()
    .HasOne<Physiotherapist>(pf => pf.IntakeDoneBy)
    .WithMany()
    .HasForeignKey(pf => pf.IntakeDoneById)
    .OnDelete(DeleteBehavior.NoAction);

    modelBuilder.Entity<PatientFile>()
    .HasOne<Physiotherapist>(pf => pf.Physiotherapist)
    .WithMany()
    .HasForeignKey(pf => pf.PhysiotherapistId)
    .OnDelete(DeleteBehavior.NoAction);

    modelBuilder.Entity<PatientFile>()
    .HasOne<Physiotherapist>(pf => pf.Supervisor)
    .WithMany()
    .HasForeignKey(pf => pf.SupervisorId)
    .OnDelete(DeleteBehavior.NoAction);
}
  • 第三步:重新执行Add-Migration InitPatientFileRelation命令生成新的迁移文件,打开新生成的迁移代码,确认三个外键的onDelete参数均为ReferentialAction.NoAction
  • 第四步:执行Update-Database命令完成数据库更新

该修改完全符合业务需求:删除物理治疗师时不会级联删除关联的患者档案,需要手动处理关联数据后再删除物理治疗师,同时绕过了SQL Server的级联路径校验。

内容的提问来源于stack exchange,提问作者Stijn van Veen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 11:36:03