问题
I'm trying to map 2 types (user -> languages) using 3 tables (user - junction table - languages), and looks like the modelBuilder is expecting both types to have a reference to each other (like user.languagesSpoken, and language.UsersSpeaking). So basically I can build something like modelBuilder.Entity<User>().HasMany(x=>x.LanguagesSpoken).WithMany(x=>x.UsersSpeaking)
.
I don't need a reference from language to user, however - and can't figure out how to map that..
Also, is there a way to specify a junction table name ?
Thanks!
回答1:
The following will do the trick:
public class User
{
public int UserId { get; set; }
public virtual ICollection<Language> LanguagesSpoken { get; set; }
}
public class Language
{
public int LanguageId { get; set; }
public int Name { get; set; }
}
public class Context : DbContext
{
public DbSet<User> Products { get; set; }
public DbSet<Language> Languages { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasMany(x => x.LanguagesSpoken)
.WithMany()
.Map(c =>
{
c.ToTable("yourDesiredName");
});
}
}
来源:https://stackoverflow.com/questions/5188958/how-to-map-many-to-many-relationships-in-entity-framework-ctp5