如果您查看docs 和other docs,您可以看到您可以访问导航,但在文档中指出这可能会在以后更改。 Do not depend on the join type being Dictionary<string, object> unless this has been explicitly configured.
所以我会手动创建一个JoinTable,真的没那么难:
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public List<BookGenre> BookGenres { get; set; }
}
public class Genre
{
public int Id { get; set; }
public string Name { get; set; }
public List<BookGenre> BookGenres { get; set; }
}
public class BookGenre
{
public int GenreId { get; set; }
public int BookId { get; set; }
public Genre Genre { get; set; }
public Book Book { get; set; }
}
如果您觉得有能力,您可以添加Fluent-api 配置,这样您就可以尽可能少地依赖 EF。在您的上下文中的OnModelCreatingMethod 或您单独的Configuration 文件中添加(可选):
builder.Entity<BookGenre>()
.ToTable("BookGenre")
.HasKey(_ => new { _.BookId, _.GenreId });
builder.Entity<BookGenre>()
.Property(_ => _.BookId)
.ValueGeneratedNever();
builder.Entity<BookGenre>()
.Property(_ => _.GenreId)
.ValueGeneratedNever();
builder.Entity<BookGenre>()
.HasOne(_ => _.Book)
.WithMany(_ => _.BookGenres)
.HasForeignKey(_ => _.BookId);
builder.Entity<BookGenre>()
.HasOne(_ => _.Genre)
.WithMany(_ => _.BookGenres)
.HasForeignKey(_ => _.GenreId);
您还需要将 JoinTable 添加到您的上下文中:
public DbSet<BookGenre> BookGenreRelations { get; set; }
现在你可以添加新的关系了:
this.myContext.BookGenreRelations.Add(new BookGenre {
BookId = myBookId,
GenreId = myGenreId,
});
this.myContext.SaveChanges();
注意:在上述示例中,您也可以使用async 版本。