EF - Code First FOREIGN KEY约束可能导致循环或多个级联路径

时间:2014-05-12 19:27:02

标签: c# sql entity-framework code-first asp.net-web-api

我一直在尝试做一些实体框架代码优先,但我坚持'FOREIGN KEY约束可能导致循环或多个级联路径。问题

以下是我的课程:

public class Course
{
    public Course()
    {
        this.Subject = new HashSet<Subject>();
        this.Student = new HashSet<Student>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string Shift { get; set; }
    public int Room { get; set; }

    public virtual ICollection<Subject> Subject { get; set; }
    public virtual ICollection<Student> Student { get; set; }
}

public class Subject
{
    public Subject()
    {
        this.Deliverable = new HashSet<Deliverable>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public int StartsAt { get; set; }
    public int FinishesAt { get; set; }
    public System.TimeSpan Weekdays { get; set; }
    public int CourseId { get; set; }
    public int TeacherId { get; set; }

    public virtual Course Course { get; set; }
    public virtual Teacher Teacher { get; set; }
    public virtual ICollection<Deliverable> Deliverable { get; set; }
}

public class Student : Person
{
    public Student()
    {
        this.Deliverable = new HashSet<Deliverable>();
    }

    public decimal Average { get; set; }
    public int CourseId { get; set; }

    public virtual Course Course { get; set; }
    public virtual ICollection<Deliverable> Deliverable { get; set; }
}

public class Teacher : Person
{
    public Teacher()
    {
        this.Subject = new HashSet<Subject>();
    }


    public virtual ICollection<Subject> Subject { get; set; }
}

public class Deliverable
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Mark { get; set; }
    public System.DateTime DeliveredDate { get; set; }
    public bool Delivered { get; set; }
    public System.DateTime AnnounceDate { get; set; }
    public int SubjectId { get; set; }
    public int StudentId { get; set; }

    public virtual Subject Subject { get; set; }
    public virtual Student Student { get; set; }
}

我认为这是一个引用循环错误,但我无法实现如何解决它的方法。我正在使用Web API,我可以更改模型,所以请随意修改它。可以使用FluentAPI解决这个问题吗?

这是例外。它是我第一次执行应用程序时抛出的:

'在表'学生'上引入FOREIGN KEY约束'FK_dbo.Students_dbo.Courses_CourseId'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。

1 个答案:

答案 0 :(得分:0)

您必须使用Fluent-API来禁用删除/更新。为此,请修改OnModelCreating方法:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<Course>().HasMany(c => c.Student).WillCascadeOnDelete(false);
}

我不确定是导致课程的课程课程还是学生课程,如果这不起作用,请尝试在您的学生课程上执行“WillCascadeOnDelete(false)”。