EF 6两个参考文献中的级联

本文关键字:级联 参考文献 6两 EF | 更新日期: 2023-09-27 18:27:55

尽管有多种解决方案可以解决此类问题,但它们不允许使用多个级联路径,而只是禁用了从一个引用中删除级联选项。

但我想允许从两个引用中删除级联

例如,在以下情况下,无论删除学生还是删除课程,都应删除绩效表信息

    public class Course
    {
       public int Id { get; set; }
       public string Name { get; set; }
       public string Type { get; set; }
       public string Department { get; set; }
       public int TeacherId { get; set; }
       public virtual Teacher Teacher { get; set; }
       public virtual ICollection<Performance> Performances { get; set; }
    }
    public class Student
    {
       public int Id { get; set; }
       public string Name { get; set; }
       public int StudentDetailId { get; set; }
       public virtual StudentDetail StudentDetailId { get; set; }
       public virtual ICollection<Performance> Performances { get; set; }
    }  
    public class Performance
    {
       public int Id { get; set; }
       public string Grade { get; set; }
       public int Attendance { get; set; }
       public int Activity { get; set; }
       [Required]
       public int StudentId { get; set; }
       [ForeignKey("StudentId")]
       public virtual Student Student { get; set; }
       [Required]
       public int CourseId { get; set; }
       [ForeignKey("CourseId")]
       public virtual Course Course { get; set; }
    }

我还试图通过在两个外键中添加ON DELETE CASCADE ON UPDATE CASCADE来手动修改数据库,但SQL server不允许我这样做。使用以上代码,我得到以下消息:

在表"Performance"上引入FOREIGN KEY约束"FK_dbo.Performance_dbo.Curse_CurseId"可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。无法创建约束。

如果我保留一个级联删除和其他引用可选,问题就会消失:

public class Performance
{
    public int Id { get; set; }
    public string Grade { get; set; }
    public int Attendance { get; set; }
    public int Activity { get; set; }
    [Required]
    public int StudentId { get; set; }
    [ForeignKey("StudentId")]
    public virtual Student Student { get; set; }
    // [Required]
    public int? CourseId { get; set; }
    [ForeignKey("CourseId")]
    public virtual Course Course { get; set; }
 }

请建议从两个引用中级联删除的方法。

EF 6两个参考文献中的级联

我不认为你真的可以用实体框架或SQL Server自动做到这一点(请参阅Alan对这个问题的回答)。这是SQL Server多年来一直存在的问题,显然在SQL Server 2014中仍未解决。

据我所见,你有两个选择:

1) 创建一个触发器,该触发器将在删除StudentCourse时自动删除Performance信息。

2) 使用EF执行手动删除,在删除StudentCourse时循环遍历Performance记录并删除它们。(不是最好的选择,因为EF在应用程序端运行)