代码之家  ›  专栏  ›  技术社区  ›  TheCloudlessSky

代码优先的多对多关系EF4

  •  9
  • TheCloudlessSky  · 技术社区  · 16 年前

    在EF4代码第一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 for user和fk for profile。我怎么画这个?

    编辑:我了解如何使用 ICollection<User> 属性上 Profile 但我真的不想有一个相反的导航属性,当它应该是“用户有许多配置文件”。

    2 回复  |  直到 15 年前
        1
  •  8
  •   TheCloudlessSky    16 年前

    编辑 :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

        2
  •  5
  •   Seth Paulson    15 年前

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

    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作为键。