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 def
You haven't to create a separate Model
for association between to models in a many-to-many relationship. Really the ArtistsGenres
is not necessary. So, remove it, and you just have to change your modelBuilder
to this one:
modelBuilder.Entity()
.HasMany(c => c.Genres)
.WithMany(x => x.Artists)
.Map(a => {
a.ToTable("ArtistsGenres");
a.MapLeftKey("ArtistId");
a.MapRightKey("GenreId");
});
It will use the ArtistsGenres
table to map a many-to-many relationship between Artists
table and
Genres
table automatically.
Note: When you define the ArtistsGenres
model, EF will not look at it as a relationship,
because you tell him that Hey EF, I have another model named ArtistsGenres
! Please manage it for me!!!
Your new entities and dbcontext will be these:
public class Artist {
public long Id { get; set; }
public string Name { get; set; }
public ICollection Genres { get; set; }
}
public class Genre {
public long Id { get; set; }
public string Title { get; set; }
public ICollection Artists { get; set; }
}
public class MusicDB : DbContex {
public DbSet Artists { get; set; }
public DbSet Genres { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Entity()
.HasMany(c => c.Genres)
.WithMany(x => x.Artists)
.Map(a => {
a.ToTable("ArtistsGenres");
a.MapLeftKey("ArtistId");
a.MapRightKey("GenreId");
});
}
Let me know if you have any questions or need clarifications on any part.