c# - 首先编码与关系表中属性的多对多关系

标签 c# entity-framework many-to-many code-first dbcontext

我想用关系表创建关系属性。下面是引用代码。但代码创建了 2 个表 BookStudents 和 BookStudents1。其中一个具有没有外键的关系属性,另一个创建没有属性但具有外键的表。我该如何解决这个问题?

public class BookStudent
{
    [Key, Column(Order = 0)]
    public int BookID { get; set; }
    [Key, Column(Order = 1)]
    public int StudentID { get; set; }
    public DateTime FromDate { get; set; }
    public DateTime ToDate { get; set; }
}


public class Context : DbContext
{
    public Context() : base("name=DefaultConnection") { }
    public DbSet<Book> Books { get; set; }
    public DbSet<Student> Students { get; set; }
    public DbSet<BookStudent> BookStudents { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Book>().HasMany<Student>(t => t.Students).WithMany(t => t.Books).Map(t =>
        {
            t.MapLeftKey("BookId");
            t.MapRightKey("StudentId");
            t.ToTable("BookStudents");
        });
    }
}

最佳答案

在代码优先中,很多情况下我们不需要在 OnModelCreating 上显式定义关系。使用下面的代码这将解决您的问题。

public class BookStudent
{
    [Key, Column(Order = 0)]
    public int BookID { get; set; }
    [Key, Column(Order = 1)]
    public int StudentID { get; set; }
    public DateTime FromDate { get; set; }
    public DateTime ToDate { get; set; }

    //below two lines will define foreign key
    public Student Student { get; set; }
    public Book Book { get; set; }
}


public class Context : DbContext
{
    public Context() : base("name=DefaultConnection") { }
    public DbSet<Book> Books { get; set; }
    public DbSet<Student> Students { get; set; }
    public DbSet<BookStudent> BookStudents { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //remove below code
        //modelBuilder.Entity<Book>().HasMany<Student>(t => t.Students).WithMany(t => t.Books).Map(t =>
        //{
        //    t.MapLeftKey("BookId");
        //    t.MapRightKey("StudentId");
        //    t.ToTable("BookStudents");
        //});
    }
}

关于c# - 首先编码与关系表中属性的多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26511088/

相关文章:

c# - 为初始加载编译后的 ASP.Net MVC 切换文化

c# - ASP.NET 应用程序如何检查用于请求的代理?

django - Django Haystack-在非索引多对多字段中搜索

c# - 使用 Entity Framework 时实现业务逻辑

c# - 对派生的 mvc 模型使用单一 View

entity-framework - 如何重命名应用于数据库的最后一个 Entity Framework 迁移

entity-framework - 带有部分更新的 Entity Framework 验证

c# - 如何将复杂类型包含到实体索引中?

mysql - 与 friend 的多对多关系

java - 与额外列的多对多关联