我想用关系表创建关系属性。以下是参考代码。但是代码创建了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");
//});
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句