c# - Entity Framework 代码优先通过关系表导航属性

标签 c# asp.net entity-framework ef-code-first code-first

我正在尝试使用一些 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/

相关文章:

c# - 处理 Multi-Tenancy 站点中的数据访问

c# - 如何从数据库的两个表中填充 ObservableCollection?

wcf - 如何防止 .NET 实体中的私有(private)属性通过服务公开为公共(public)属性?

c# - 如何在剑道下拉列表中绑定(bind)字符串列表

c# - 使用 .Net6 Windows 10 在 Visual Studio Code for OmniSharp 上出错

c# - Web 形式的智能卡授权

c# - 在 EntityFramework 中删除具有相关实体的实体

c# - 将空值绑定(bind)到 Web 用户控件的属性

c# - 如何找出 iis7 中的 404 错误处理程序中缺少哪个请求路径?

c# - 如何对随时间变化的表格数据进行建模并能够回溯到任何点