紀錄 Entity Framework v6 Code First 與 Dapper Contrib 的模型建立時,資料表索引的設定;順便替懶得查文件的同事紀錄。
以下資料表模型參考 Northwind 建立,使用 Region 與 Order Details


Entity Framework
當資料庫資料表單一 Primary Key 時,透過 Attribute 設定 [Key] 即可。
| 12
 3
 4
 5
 6
 7
 8
 
 | public class Regions{
 [Key]
 public int RegionID { get; set; }
 
 public string RegionDescription { get; set; }
 
 }
 
 | 
當資料表是複合索引 (Composite keys) 時,針對是索引的欄位還是使用 [Key] 來設定,但是必須設定排序的順序,否則會出現錯誤;當複合鍵時,除了 [Key] 外,尚需要設定 [Column(Order = n)]
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 
 | public class OrderDetails{
 [Key]
 [Column(Order = 1)]
 public int OrderID { get; set; }
 [Key]
 [Column(Order = 2)]
 public int ProductID { get; set; }
 
 public decimal UnitPrice { get; set; }
 
 public short Quantity { get; set; }
 
 public float Discount { get; set; }
 
 }
 
 | 
Dapper Contrib
Dapper Contrib 與 Entity Framework 不同,索引的 Attribute 隨著是否自動增值有所差異,自動增值的索引直接使用 [Key] , 非自動增值的索引使用 [ExplicitKey] 。
所以 Dapper Contrib 是已針對索引的自動增值與否進行設定,不管是單一鍵還是複合鍵都是如此。
以下為單一鍵的範例:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 
 | public class Regions
 {
 [Key]
 public int RegionID { get; set; }
 
 public string RegionDescription { get; set; }
 
 }
 
 
 public class Regions
 {
 [ExplicitKey]
 public int RegionID { get; set; }
 
 public string RegionDescription { get; set; }
 
 }
 
 | 
以下為複合鍵的範例,假設當兩個複合鍵皆是自動增值或是皆非自動增值
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 
 | public class OrderDetails
 {
 [Key]
 public int OrderID { get; set; }
 [Key]
 public int ProductID { get; set; }
 
 public decimal UnitPrice { get; set; }
 
 public short Quantity { get; set; }
 
 public float Discount { get; set; }
 
 }
 
 public class OrderDetails
 {
 [ExplicitKey]
 public int OrderID { get; set; }
 [ExplicitKey]
 public int ProductID { get; set; }
 
 public decimal UnitPrice { get; set; }
 
 public short Quantity { get; set; }
 
 public float Discount { get; set; }
 
 }
 
 | 
參考資料
附上使用 LinqPad 的簡單範例, Entity Framework 、 Dapper Contrib ,使用前記得引用參考。