Note that there are some explanatory texts on larger screens.

plurals
  1. POHow Model n--n relationship in EF Code First to automatically generated views work correctly?
    primarykey
    data
    text
    <p>I use EF Code First and have a problem in n-n relationship, assume we have a singer that sing in some genres, so we need this models: Artist, Genre, and ArtistsGenres, I define Models as following:</p> <p>This is My Artist Model:</p> <pre><code>public class Artist { public long Id { get; set; } public string Name { get; set; } public ICollection&lt;Genre&gt; Genres { get; set; } } </code></pre> <p>And My Genre Model:</p> <pre><code>public class Genre { public long Id { get; set; } public string Title { get; set; } public ICollection&lt;Artist&gt; Artists { get; set; } } </code></pre> <p>And my context class:</p> <pre><code>public class MusicDB : DbContex { public DbSet&lt;Artist&gt; Artists { get; set; } public DbSet&lt;Genre&gt; Genres { get; set; } public DbSet&lt;ArtistsGenres&gt; ArtistsGenres { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity&lt;Artist&gt;() .HasMany(a =&gt; a.Genres) .WithMany(g =&gt; g.Artists) .Map(model =&gt; { model.ToTable("ArtistsGenres"); model.MapLeftKey("Artist_Id"); model.MapRightKey("Genre_Id"); }); base.OnModelCreating(modelBuilder); } } </code></pre> <p>But there is not any relationship between Artists and Genres when MVC generate views automatically.</p> <p>For example, I need to change Genres of an Artist in edit view, in Create view I can set Genres for an Artist, or in Index View I want show genres for each Artist. But there isn't any generation for Genres in relation to Artist when MVC generate views automatically. </p> <p>I know I can access both Genres and Artists from both side but I am interesting in MVC automatically generate views as we want: for ex: for each artist show related Genres.</p> <p>How can I do this? Is my model correct? Is this true for any (n to n) relation that needs ICollection on both side? Or do I need some elements in overriding of <code>OnModelCreating</code> method in context class, for example something like this:</p> <pre><code>modelBuilder.Entity&lt;Artist&gt;() .HasMany(a =&gt; a.Genres) .WithMany(g =&gt; g.Artists); </code></pre> <p>Please help me, I don't know the exact implementation of NtoN relationship.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload