2014-10-27 71 views
0

尽管针对这些问题有多种解决方案,但它们不允许多个级联路径,而只是从一个参考中禁用删除级联选项。EF 6级联两个参考

但我想,以允许在删除级联从两个引用

例如,在以下情况下,性能表中的信息应予以删除学生是否被删除课程删除

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服务器不允许我这样做。 利用上述代码我获得以下信息:

在介绍表“性能”外键约束“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; } 
} 

请建议级联的方式,从两个引用删除。

回答

1

我不认为你实际上可以用Entity Framework或SQL Server自动执行此操作(请参阅Alan对this question的回答)。现在,这已经与SQL Server多年来一直存在的问题,显然仍然没有固定在SQL Server 2014

你,从我所看到的,2种选择:

1)创建触发器当删除StudentCourse时,将自动删除Performance信息。

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

+0

嗨谢谢你的回答。是否有可能在SQL中执行触发器,因为在某些情况下,我并不真正删除学生或课程,但有父母对象或祖父母对象来谴责学生或课程,我认为你理解我的意思是:/ – Muffin 2014-10-27 14:33:03

+0

我是非常确定,只要记录被删除,触发器就会运行,即使它是由级联完成的。 – IronMan84 2014-10-27 14:35:27

+0

http://www.mssqltips.com/sqlservertip/2733/solving-the-sql-server-multiple-cascade-path-issue-with-a-trigger/ – IronMan84 2014-10-27 14:42:11