[英]Entity Framework Code First navigation property through relational table
我正在尝试使用某些Entity Framework Code First模型设置一些导航属性。 我希望他们看起来像这个例子:
public class Course
{
[Key]
public int CourseId { get; set; }
public string CourseName { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
public class Student
{
[Key]
public int StudentId { get; set; }
public string StudentName { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
public class StudentCourses
{
[Key, Column(Order = 0)]
public int StudentId { get; set; }
public virtual Student Student { get; set; }
[Key, Column(Order = 1)]
public int CourseId { get; set; }
public virtual Course Course { get; set; }
}
因此,将在StudentCourses表中建立学生和课程的关系。 学生类的实例将自动引用所有该学生的课程,反之亦然,课程类的实例将自动引用其所有学生的课程。 并且StudentCourses类的实例将自动引用其Student和Course。 但是,当我尝试更新数据库时,似乎无法正确解释这些关系。 我在这里想念什么吗? 也许需要在上下文类中进行一些配置? 导航属性的大多数示例仅显示一对多关系导航属性。
拥有M : M
关系时,您需要按如下所示构造模型。 您不需要构造联结表。 进行数据迁移时,EF会为您创建一个。
使用约定进行模型配置。
public class Student
{
public Student()
{
this.Courses = new HashSet<Course>();
}
public int StudentId { get; set; }
public string StudentName { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
public class Course
{
public Course()
{
this.Students = new HashSet<Student>();
}
public int CourseId { get; set; }
public string CourseName { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
您的上下文类应该是这样的。
public class YourDBContext : DBContext
{
public YourDBContext () : base("Default")
{
}
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
在遵循Sampath的建议之后,我实际上决定要在关系中附加一些其他属性。 所以我最终像这样定义了StudentCourses类:
public class StudentCourses
{
[Key, Column(Order = 0)]
public int StudentId { get; set; }
public virtual Student Student { get; set; }
[Key, Column(Order = 1)]
public int CourseId { get; set; }
public virtual Course Course { get; set; }
public int Grade { get; set; }
}
所以我这样改变了学生和课程:
public class Course
{
[Key]
public int CourseId { get; set; }
public string CourseName { get; set; }
public virtual ICollection<StudentCourses> Students { get; set; }
}
public class Student
{
[Key]
public int StudentId { get; set; }
public string StudentName { get; set; }
public virtual ICollection<StudentCourses> Courses { get; set; }
}
最重要的是,我没有将StudentCourses添加到DbContext。 因此,在执行Update-Database之后,EF会自动为StudentCourses创建表,并且导航属性全部可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.