虽然此类问题有多种解决方案,但它们不允许多个级联路径,而只是从一个引用中禁用delete级联选项。
但我希望允许从两个引用中删除级联。
例如,在以下情况下,无论删除“学生”还是“课程”,都应删除性能表信息
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; }
}我还试图通过在两个外键中添加DELETE级联更新级联来手动修改数据库,但是SQL server也不允许我这样做。通过上面的代码,我得到以下消息:
在表‘性能’上引入外键约束'FK_dbo.Performance_dbo.Course_CourseId‘可能会导致循环或多个级联路径。指定“删除不操作”或“更新不操作”,或修改其他外键约束。无法创建约束。
如果我保留一个级联删除和其他引用(可选),问题就会消失:
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; }
}请建议一种从两种参考资料中删除的方法。
发布于 2014-10-27 14:24:04
我不认为您实际上可以使用实体框架或Server自动完成此操作(请参阅Alan对this question的回答)。这是Server多年来一直存在的问题,显然在Server 2014中仍未解决。
据我所见,你有两个选择:
1)创建一个触发器,在删除Performance或Course时自动删除Course信息。
2)使用EF执行手动删除,在删除Performance或Course时循环遍历它们并删除它们。(这不是最好的选择,因为EF运行在应用程序端)
https://stackoverflow.com/questions/26589100
复制相似问题