簡體   English   中英

Code-First EF4中的多對多關系

[英]Many-To-Many Relationship in Code-First EF4

您如何在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 for User和FK for Profile。 我該如何映射?

編輯:我知道如何在Profile具有ICollection<User>屬性的當前映射,但我真的不希望有一個相反的導航屬性,它應該是“用戶有很多配置文件”。

編輯 :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

對於多對多關系,您應該在兩側包含導航屬性並使其成為虛擬(以利用延遲加載)

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為Keys。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM