Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

many to many EF7

Models:

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)
{
    modelBuilder.Entity<Film>()
                    .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?

like image 409
Artem Shaban Avatar asked Feb 07 '15 13:02

Artem Shaban


2 Answers

The docs for EF7 says how this can be achived: 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; }
        }
like image 57
Nyegaard Avatar answered Oct 16 '22 23:10

Nyegaard


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.

like image 23
Gert Arnold Avatar answered Oct 17 '22 01:10

Gert Arnold