型号:
public partial class Film
{
public int FilmID { get; set; }
public virtual ICollection<Genre> Genres { get; set; }
}
public class Genre
{
public int GenreID { get; set; }
public virtual ICollection<Film> Films { get; set; }
}
使用EF6 OnModelCreating
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Film>()
.HasMany(e => e.Genres)
.WithMany(e => e.Films)
.Map(m => m.ToTable("Genre_Film").MapLeftKey("Films_IdFilm").MapRightKey("Genres_IdGenre"));
}
我使用SQLite。我如何使用EF7做同样的事情?
答案 0 :(得分:9)
EF7的文档说明了如何实现这一目标:http://docs.efproject.net/en/latest/modeling/relationships.html#many-to-many
modelBuilder.Entity<PostTag>() .HasOne(pt => pt.Post) .WithMany(p => p.PostTags) .HasForeignKey(pt => pt.PostId);
modelBuilder.Entity<PostTag>()
.HasOne(pt => pt.Tag)
.WithMany(t => t.PostTags)
.HasForeignKey(pt => pt.TagId);
public class PostTag
{
public int PostId { get; set; }
public Post Post { get; set; }
public int TagId { get; set; }
public Tag Tag { get; set; }
}
答案 1 :(得分:7)
映射API将在EF 7中更改。已提出更多intuitive one to many API的提案。在那里有许多短语:
我们希望多对多API与一对多和一对一API非常相似。
但它尚未在当前来源中实施。在为测试创建的上下文中,它说:
// TODO: Many-to-many
//modelBuilder.Entity<TSupplier>().ForeignKeys(fk => fk.ForeignKey<TProduct>(e => e.SupplierId));
关于我能找到的所有相关信息。
我当然希望EF7在这方面能够向后兼容。