EF CF如何创建一个具有三个外键的表

时间:2016-03-07 14:00:33

标签: entity-framework

我的模特学生有他所有科目的集合,每个科目都收集了教育比赛。

public class Subject
{
     public int SubjectID { get; set; }
     public string SubjectName {get; set; }
     public ICollection<Student> { get; set; }
}

public class EducationalMatches
{
     public int EducationalMatchesID { get; set; }
     public int Number { get; set; }
     public string Name { get; set; }
}

public class Student
{
     public int StudentID { get; set; }
     public Icollection<AllStudentSubjects> AllStudentSubjects{ get; set; }
}


public class AllStudentSubject
{
     public int AllStudentSubjectID { get; set; }
     public Subject Subject { get; set; }
     public ICollection<EducationalMatches> Educations { get; set; }
}

我希望在DB中会出现一个看起来像这样的表:

tableID
StudentID
SubjectID
EducationMatchesID

但没有出现这样的表格。 有谁有想法?

1 个答案:

答案 0 :(得分:0)

拥有模型是不够的,您需要覆盖OnModelCreating方法(默认情况下它是空的)。加上EF希望能够“扭转”#39;例如,如果学生有一个主题集合,主题应该有一个学生集合(多对多关系)

在AllStudentSubject的情况下,它应该是这样的(没有测试)

protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<AllStudentSubject>() .HasKey(a => a.AllStudentSubjectID ) //Primary key, I prefer [Key] attribute, but this also works .HasRequired(a => a.Student) //Property in AllStudentSubject .WithMany(s => s.AllStudentSubjects) // Collection property in Student class .HasForeignKey(a => a.StudentId)//Second property in AllStudentSubject //For Student, you do not have to write this all again, just the primary key modelBuilder.Entity<Student>() .HasKey(a => a.StudentId ) //I like to move 'simple' declarations like this to the top }

对于其他两个实体,您必须这样做。 这是一个伟大的article,其中包含所有概念的解释