【发布时间】: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