Many-To-Many Relationship in Code-First EF4

前端 未结 2 1871
情歌与酒
情歌与酒 2020-12-29 13:53

How do you represent a many-to-many relationship in the EF4 Code-First CTP3?

For example if I have the following classes:

class User
{
    public int         


        
2条回答
  •  暖寄归人
    2020-12-29 14:36

    With many to many relationships you should include navigation properties on both sides and make them virtual (to utilize lazy loading)

    class User
    {
      public int Id { get; set; }
      public string Name { get; set; }
      public virtual ICollection Profiles { get; set; }
    }
    
    class Profile
    {
      public int Id { get; set; }
      public string Name { get; set; }
      public virtual ICollection Users { get; set; }
    }
    

    Then with that setup you can define your many to many relationship (you can also let entity framework do it for you but I don't like the naming conventions it uses.)

            modelBuilder.Entity().
                HasMany(p => p.Users).
                WithMany(g => g.Profiles).
                Map(t => t.MapLeftKey("ProfileID")
                    .MapRightKey("UserID")
                    .ToTable("UserProfiles"));
    

    This will give you a table named UserProfiles with UserID and ProfileID as Keys.

提交回复
热议问题