一、在 UML 圖中識別 N\:N 關系

  1. 打開 UML 類圖,尋找兩個實體之間都標記為 “*”(Many)的關聯。
  2. 如示例圖中:Pokemon ── OwnerPokemon ── Category,都需通過中間表實現。

二、創建 Join 表實體(關聯表)

  1. Models 內新增 PokemonOwner.cs

    public class PokemonOwner
    {
       public int PokemonId { get; set; }
       public Pokemon Pokemon { get; set; }
    
       public int OwnerId { get; set; }
       public Owner Owner { get; set; }
    }
  2. 同理創建 PokemonCategory.cs

    public class PokemonCategory
    {
       public int PokemonId { get; set; }
       public Pokemon Pokemon { get; set; }
    
       public int CategoryId { get; set; }
       public Category Category { get; set; }
    }

    Join 表同時持有兩個外鍵和對應導航屬性,用于存儲多對多關系。


三、在實體中添加集合導航屬性(“一”端)

  1. Pokemon 類新增:

    public ICollection < PokemonOwner >   PokemonOwners   { get; set; }
    public ICollection < PokemonCategory > PokemonCategories { get; set; }
  2. Owner 類新增:

    public ICollection < PokemonOwner > PokemonOwners { get; set; }
  3. Category 類新增:

    public ICollection < PokemonCategory > PokemonCategories { get; set; }

    通過集合導航屬性,EF Core 可識別并查詢關聯數據。


四、在 Join 實體中反向添加導航屬性(“多”端)

  1. PokemonOwnerPokemonCategory 已在定義時包含雙向導航,便于從關聯表訪問雙方實體。
  2. 確保所有外鍵字段類型與主實體主鍵一致,避免類型不匹配。

五、驗證模型完整性與調試小技巧

  1. 手動檢查各實體及 Join 實體中的數據類型和屬性名稱,避免拼寫或類型錯誤。
  2. 在 VS Code 中,使用右鍵 Go to Definition 快速跳轉查看實體定義,提升開發效率。

小結與下一步

通過本篇,您已掌握手動構建 N\:N 關系的核心步驟,為更復雜的數據模型打下堅實基礎。

原文引自YouTube視頻:https://www.youtube.com/watch?v=oOUSvRc3FMo

上一篇:

ASP.NET Core Web API 一對多關系詳解:POCO、外鍵與實體映射

下一篇:

ASP.NET Core Web API DTO 實踐:Data Transfer Object 全方位解析
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費