实体框架迁移级联删除警告
本文关键字:删除 警告 级联 迁移 框架 实体 | 更新日期: 2023-09-27 18:05:54
我有两个相互关联的类(一对多),我认为我已经正确设置了属性,但是当我运行Update-Database
命令进行迁移时,我得到以下错误:
引入FOREIGN KEY约束"FK_dbo.ParentEnrollment_dbo。表上的CellGroup_CellGroupID'ParentEnrollment'可能导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他外部键约束。无法创建约束或索引。见以前的错误。
两个类:
[Table("CellGroup")]
public class CellGroup : BaseEntity
{
public Guid AcademicYearID { get; set; }
[ForeignKey("AcademicYearID")]
public virtual AcademicYear AcademicYear { get; set; }
public Guid LeaderID { get; set; }
[ForeignKey("LeaderID")]
public virtual Parent Leader { get; set; }
public Guid PreviousGroupID { get; set; }
[ForeignKey("PreviousGroupID")]
public virtual CellGroup PreviousGroup { get; set; }
public string Name { get; set; }
public int MaximumSize { get; set; }
public virtual ICollection<ParentEnrollment> Parents { get; set; }
}
和
[Table("ParentEnrollment")]
public class ParentEnrollment : BaseEntity
{
public Guid ParentID { get; set; }
[ForeignKey("ParentID")]
public virtual Parent Parent { get; set; }
public Guid AcademicYearID { get; set; }
[ForeignKey("AcademicYearID")]
public virtual AcademicYear AcademicYear { get; set; }
public bool FirstTimeEnrolling { get; set; }
public string HSLDAAccountNumber { get; set; }
public DateTime HSLDARenewalDate { get; set; }
public string CurrentChurch { get; set; }
public string CurrentChurchContact { get; set; }
public string CurrentChurchPhone { get; set; }
public Guid CellGroupID { get; set; }
[Required]
[ForeignKey("CellGroupID")]
public virtual CellGroup CellGroup { get; set; }
public bool VolunteerBuyOut { get; set; }
public Guid VolunteerPositionID { get; set; }
[ForeignKey("VolunteerPositionID")]
public virtual VolunteerPosition VolunteerPosition { get; set; }
public string VolunteerPositionNotes { get; set; }
public virtual ICollection<StudentEnrollment> StudentEnrollments { get; set; }
}
我在CellGroup类上只有Parents属性,所以我可以很容易地访问该单元格组中的注册列表。我试图删除属性,看看它是否清除了警告/错误,但它没有。有人能指出我的模型哪里出了问题吗?
这个错误说明你不能从表ParentEnrollment
引入一个外键到表CellGroup
,因为这将创建多个级联路径,这在SQL Server上是不允许的。
根据您发布的代码,两个表都与表Parent
和AcademicYear
有关系,它们位于不可空的FK列上,因此EF默认情况下将在删除时启用级联。从ParentEnrollment
到CellGroup
的另一个FK将有多个级联路径,例如Parent
到CellGroup
到ParentEnrollment
和Parent
到ParentEnrollment
,这导致了您的错误。删除Parent
属性并不能解决这个问题,因为仍然存在从表AcademicYear
开始的级联路径问题。
所以你必须为你的外键禁用级联删除,这必须在你的DbContext中使用Fluent API来完成,像这样:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ParentEnrollment>()
.HasRequired(m => m.CellGroup)
.WithMany(m => m.Parents)
.HasForeignKey(m => m.CellGroupID)
.WillCascadeOnDelete(false);
}