首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >两个参考文献中的EF 6级联

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

Stack Overflow用户
提问于 2014-10-27 13:52:07
回答 1查看 57关注 0票数 0

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

但我希望允许从两个引用中删除级联。

例如,在以下情况下,无论删除“学生”还是“课程”,都应删除性能表信息

代码语言:javascript
运行
复制
    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‘可能会导致循环或多个级联路径。指定“删除不操作”或“更新不操作”,或修改其他外键约束。无法创建约束。

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

代码语言:javascript
运行
复制
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; }
 }

请建议一种从两种参考资料中删除的方法。

EN

回答 1

Stack Overflow用户

发布于 2014-10-27 14:24:04

我不认为您实际上可以使用实体框架或Server自动完成此操作(请参阅Alan对this question的回答)。这是Server多年来一直存在的问题,显然在Server 2014中仍未解决。

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

1)创建一个触发器,在删除PerformanceCourse时自动删除Course信息。

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26589100

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档