many to many EF7

c# entity-framework-core



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 using EF6

protected override void OnModelCreating(DbModelBuilder modelBuilder)
                    .HasMany(e => e.Genres)
                    .WithMany(e => e.Films)
                    .Map(m => m.ToTable("Genre_Film").MapLeftKey("Films_IdFilm").MapRightKey("Genres_IdGenre"));

I use SQLite. How I can do the same using EF7?

2/15/2016 5:21:31 AM

Accepted Answer

The docs for EF7 says how this can be achived:

            .HasOne(pt => pt.Post)
            .WithMany(p => p.PostTags)
            .HasForeignKey(pt => pt.PostId);
            .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; }
12/15/2015 3:05:36 PM

Popular Answer

The mapping API will change in EF 7. There has been a proposal for a more intuitive one to many API. There is a short word on many to many there:

We expect the many-to-many API to be very similar to the one-to-many and one-to-one APIs.

But it's not yet implemented in the current source. In a context created for tests it says:

// TODO: Many-to-many
//modelBuilder.Entity<TSupplier>().ForeignKeys(fk => fk.ForeignKey<TProduct>(e => e.SupplierId));

That's about all I can find about it.

I surely hope that EF7 will be backward compatible in this area.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow