【问题标题】:EF 6 Cascades from both references来自两个参考的 EF 6 级联
【发布时间】:2014-10-27 13:52:07
【问题描述】:

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

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

例如在以下情况下,无论是删除Student还是删除Course,都应该删除Performance表信息

    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.Course_CourseId”可能会导致循环或多个级联路径。指定 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; }
 }

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

【问题讨论】:

    标签: c# sql-server entity-framework code-first cascade


    【解决方案1】:

    我认为您实际上不能使用 Entity Framework 或 SQL Server 自动执行此操作(请参阅 Alan 对 this question 的回答)。多年来,这一直是 SQL Server 的一个持续问题,显然在 SQL Server 2014 中仍未解决。

    据我所知,您有 2 个选项:

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

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

    【讨论】:

    • 您好,谢谢您的回答。是否可以在 SQL 中执行触发器,因为在某些情况下,我并没有真正删除学生或课程,而是存在级联学生或课程的父对象或祖父对象,我想你理解我的意思的问题:/
    • 我很确定触发器会在记录被删除的任何时候运行,即使它是由级联完成的。
    猜你喜欢
    • 2012-12-29
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 2013-10-30
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多