Entity Framework 實戰 – 多對多自我關聯 Many to Many , Self Referencing 模型實作 (一)

在我們軟體開發過程中,我們會遇到一種特殊模型實體關係,例如一個線上商品系統,會有產品資料表(Product Table),以及記錄產品的【相關產品】和該產品本身可以被關聯的上層【相關產品】,感覺很繞口,下圖我截取一個 ER-D 示例圖:

image

上圖ERD 關聯存在所謂的多對多關係 (Many to Many)而且又是自我關聯(自身關聯,Self Referencing),本身的主要邏輯是 RelatedProduct 這個Table,擔任一個用來記錄多對多關聯記錄的中繼Table,RelatedProduct Table包含了2個欄位(ProductID、RelatedProductID),2個欄位都是參考(Referencing)到 Product Table的 ProductID 主鍵值 ( Primary Key ),透過這樣的技巧可以表達一個產品可以關聯多個相關產品,反之也可以表達一個產品可以被多少產品有所關聯….

但現在我要教大家實作一個只需要在 Entity Framework 建立一個 Product Model (POCO),然後透過一些程式寫法技巧,來達成 這種商業資料模型  – 》 多對多自我關聯 Many to Many , Self Referencing 。

首先讓我們用 Visual Studio 開發工具來先新增一個程式專案,在此我程式專案命名為 EF6_ManyToManyAndSelf,然後按確定。

image

接下來,我們需要透過 NuGet來安裝 EntityFramework ,

image

image

在上圖執行安裝按鈕後,後續 NuGet 就會開始安裝 EntityFramewok , 目前 Allen 裝的版本為 6.1.3 穩定版,安裝過程可能會等候一點點時間,裝完後,你會發現專案的參考對了2個參考項目

image

確定沒問題後,接下來我們來新增一個 Product Class ,用來代表 Product table 的對應,完整程式碼如下:

image

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.ComponentModel.DataAnnotations;
   4:  using System.ComponentModel.DataAnnotations.Schema;
   5:  using System.Linq;
   6:  using System.Text;
   7:  using System.Threading.Tasks;
   8:   
   9:  namespace EF6_ManyToManyAndSelf
  10:  {
  11:      [Table("Product", Schema = "dbo")]
  12:      public class Product
  13:      {
  14:          public Product()
  15:          {
  16:              RelatedProducts = new HashSet<Product>();
  17:              AboveProducts = new HashSet<Product>();
  18:          }
  19:   
  20:          [Key]
  21:          [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  22:          public int ProductID { get; set; }
  23:   
  24:          public string ProductName { get; set; }
  25:   
  26:          public decimal Price { get; set; }
  27:   
  28:          /// <summary>
  29:          /// 記錄此產品的多個相關的產品
  30:          /// </summary>
  31:          public virtual ICollection<Product> RelatedProducts { get; set; }
  32:   
  33:          /// <summary>
  34:          /// 記錄此產品被那些上層產品標示為相關的產品
  35:          /// </summary>
  36:          public virtual ICollection<Product> AboveProducts { get; set; }
  37:   
  38:      }
  39:  }
 

    實作到這邊已經把基本的 EntityFramework 安裝進來,也把產品模型寫成一個POCO Class ,後續是更進階的 程式技巧已經背後運作解釋,請待我撰寫  Entity Framework 實戰 – 多對多自我關聯 Many to Many , Self Referencing 模型實作 (二) 的介紹。

 

網智數位-軟體開發 (軟件開發)

發表留言

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料