How to map many-to-many relationships in Entity Framework CTP5?

萝らか妹 提交于 2019-12-10 23:13:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!