我正在尝试使用一些 Entity Framework 代码优先模型设置一些导航属性。我希望它们看起来像这个例子:
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; }
}
因此,学生和类(class)的关系将在 StudentCourses 表中建立。学生类的实例将自动引用该学生的所有类(class),反之亦然,类(class)类的实例将自动引用其所有学生。 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);
}
}
关于c# - Entity Framework 代码优先通过关系表导航属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40135790/