实体框架迁移级联删除警告

时间:2015-08-02 18:36:55

标签: c# entity-framework ef-migrations

我有两个相互关联的类(一对多),我认为我已正确设置属性,但是当我为迁移运行Update-Database命令时,出现以下错误:

  

引入FOREIGN KEY约束   表上的'FK_dbo.ParentEnrollment_dbo.CellGroup_CellGroupID'   'ParentEnrollment'可能会导致循环或多个级联路径。指定   ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN   关键约束。无法创建约束或索引。见前   错误。

我的两个课程:

[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属性,因此我可以轻松访问该单元组中的注册列表。我试图删除该属性,看它是否清除了警告/错误,但它没有。有人可以找出我的模型出错的地方吗?

1 个答案:

答案 0 :(得分:2)

此错误表示您无法将表ParentEnrollment中的外键引入启用了级联删除的表CellGroup,因为这将创建多个级联路径,这在SQL Server上是不允许的。 / p>

根据您发布的代码,两个表都与表Parent以及AcademicYear有关系,这些表位于不可为空的FK列上,因此默认情况下EF将启用级联删除。使用从ParentEnrollmentCellGroup的另一个FK,将存在多个级联路径,例如ParentCellGroupParentEnrollmentParentParentEnrollment,这会导致您的错误。删除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);
}