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

时间:2014-10-22 15:22:24

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

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

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");
        });
    }
}

1 个答案:

答案 0 :(得分:2)

在代码中,首先我们不需要在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");
        //});
    }
}