多对多 EF7
many to many EF7
型号:
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; }
}
OnModelCreating 使用 EF6
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 执行相同的操作?
映射 API 将在 EF 7 中更改。有人提议提供更多 intuitive one to many API。那里有一个关于多对多的简短词:
We expect the many-to-many API to be very similar to the one-to-many and one-to-one APIs.
但是目前的源码还没有实现。在为测试创建的上下文中,它说:
// TODO: Many-to-many
//modelBuilder.Entity<TSupplier>().ForeignKeys(fk => fk.ForeignKey<TProduct>(e => e.SupplierId));
这就是我能找到的所有信息。
我当然希望 EF7 能够在这方面向后兼容。
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; }
}
型号:
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; }
}
OnModelCreating 使用 EF6
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 执行相同的操作?
映射 API 将在 EF 7 中更改。有人提议提供更多 intuitive one to many API。那里有一个关于多对多的简短词:
We expect the many-to-many API to be very similar to the one-to-many and one-to-one APIs.
但是目前的源码还没有实现。在为测试创建的上下文中,它说:
// TODO: Many-to-many
//modelBuilder.Entity<TSupplier>().ForeignKeys(fk => fk.ForeignKey<TProduct>(e => e.SupplierId));
这就是我能找到的所有信息。
我当然希望 EF7 能够在这方面向后兼容。
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; }
}