9

您如何表示 EF4 Code-First CTP3 中的多对多关系?

例如,如果我有以下课程:

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; }
}

在数据库中有一个 UserProfiles 表,其中包含用户的 FK 和配置文件的 FK。我怎样才能映射这个?

编辑:我了解当前如何在 上使用ICollection<User>属性进行映射Profile,但是当它应该是“用户有很多个人资料”时,我真的不想拥有相反的导航属性。

4

2 回答 2

8

编辑:CTP4 于昨天晚些时候(2010 年 7 月 14 日)发布,现在支持:

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


终于发现这目前是不可能的。Microsoft 正在寻求添加此功能(只有一个导航属性)。

有关详细信息,请参阅 MSDN 论坛上的此链接:http: //social.msdn.microsoft.com/Forums/en/adonetefx/thread/6920db2b-88c7-4bea-ac89-4809882cff8f

于 2010-07-14T14:34:03.897 回答
5

对于多对多关系,您应该在两侧包含导航属性并使它们成为虚拟(以利用延迟加载)

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; }
}

然后通过该设置,您可以定义多对多关系(您也可以让实体框架为您完成,但我不喜欢它使用的命名约定。)

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

这将为您提供一个名为 UserProfiles 的表,其中 UserID 和 ProfileID 作为键。

于 2011-05-13T15:46:20.247 回答