Many-To-Many Relationship in Code-First EF4

时光毁灭记忆、已成空白 提交于 2019-12-18 11:56:38

问题


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 Id { get; set; }
    public string Name { get; set; }
    public ICollection<Profile> Profiles { get; set; }
}

class Profile
{
    public int Id { get; set; }
    public string Name { get; set; }
}

In the database there is a UserProfiles table that has the FK for User and FK for Profile. How can I map this?

EDIT: I understand how to to currently map with having a ICollection<User> property on the Profile, but I really don't want to have a an opposite navigation property when it should be "Users have many profiles".


回答1:


EDIT: CTP4 was released late yesterday (July 14 2010) and there is now support for this:

modelBuilder.Entity<Post>().HasMany(p => p.Tags).WithMany();


I found out finally that this currently isn't possible. Microsoft is looking to add this feature (only one navigation property).

See this link on the MSDN forums for more information: http://social.msdn.microsoft.com/Forums/en/adonetefx/thread/6920db2b-88c7-4bea-ac89-4809882cff8f




回答2:


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<Profile> Profiles { get; set; }
}

class Profile
{
  public int Id { get; set; }
  public string Name { get; set; }
  public virtual ICollection<User> 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<Profile>().
            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.



来源:https://stackoverflow.com/questions/3148844/many-to-many-relationship-in-code-first-ef4

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