簡體   English   中英

實體框架 - 多對多?

[英]Entity Framework - Many to many?

我正在定義如下的多對多關系:

    modelBuilder.Entity<GameSessionEntry>().
         HasMany(c => c.Users).
         WithMany(p => p.GameSessionEntries).
         Map(
          m =>
          {
              m.MapLeftKey("SessionId");
              m.MapRightKey("UserId");
              m.ToTable("UserSessions");
          });

但是,我一直在:

無法創建具有列'UserId'的表'UserSessions'上的外鍵,因為無法確定主鍵列。 使用AddForeignKey fluent API完全指定外鍵。

我是數據庫工作和EntityFramework的新手 - 它要求我做什么?

這是左右反復出現的混亂,請參閱Slauma的這個解釋。 所以你只需要轉動關鍵名稱:

  m.MapLeftKey("UserId");      // Property in the HasMany call
  m.MapRightKey("SessionId");  // Property in the WithMany call

這就是我通常創建多對多表的方法(注意這不需要流暢的api配置)

public class User
{
    public int Id { get; set; }
    public virtual ICollection<UserSession> UserSessions { get; set; }
}

public class Session
{
    public int Id { get; set; }
    public virtual ICollection<UserSession> UserSessions { get; set; }
}

public class UserSession
{
    [Key]
    [Column(Order = 1)]
    public int UserId { get; set; }

    [Key]
    [Column(Order = 2)]
    public int SessionId{ get; set; }

    public virtual User User { get; set; }
    public virtual Session Session { get; set; }
}

您應該將其重寫為弱實體集,而不是擺弄多對多關系。

如果你有這種關系:

在此輸入圖像描述

您可以將其重新設計為弱實體集:

在此輸入圖像描述

通過這樣做,您可以擺脫多對多的關系,而不必將相同的數據存儲在多個表中。

有關更多信息,請訪問: http ://fileadmin.cs.lth.se/cs/Education/EDA216/lectures/dbtoh4.pdf從幻燈片87/360開始閱讀關於“關系數據模型”的演講幻燈片。

暫無
暫無

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

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