2011-05-11 68 views
43

我正在使用asp .net mvc 3,並且當我嘗試在表中插入數據時,包含2個主鍵的實體出現問題。多主鍵與asp .net mvc 3

public class LineItem 
    { 
     [Key] 
     public int OrderId { get; set;} 
     [Key] 
     public int LineNum { get; set;} 
     public string ItemId { get; set;} 
     public int Quantity { get; set;} 
     public decimal UnitPrice { get; set; } 

    } 

,當我嘗試插入,我得到這個錯誤:

無法確定類型 「ApplicationMVC3.Models.LineItem」複合主鍵 排序。使用 ColumnAttribute或HasKey方法 指定複合 主鍵的順序。

有人可以幫助我!

回答

70

假設這實際上是一個組合鍵,因爲你不能有2個主鍵......錯誤消息告訴你該做什麼,即添加一個訂單。您可以通過將[Column(Order = 0)][Column(Order = 1)]添加到您的關鍵字欄來完成此操作。

對於示例:

public class LineItem 
    { 
     [Key][Column(Order = 0)] 
     public int OrderId { get; set;} 
     [Key][Column(Order = 1)] 
     public int LineNum { get; set;} 
     public string ItemId { get; set;} 
     public int Quantity { get; set;} 
     public decimal UnitPrice { get; set; } 

    } 
+3

感謝您的幫助,我添加此 [關鍵] [列(訂單= 0)] 公衆詮釋的OrderId {獲得;設置;} [Key] [Column(Order = 1)] public int LineNum {get;設置;} 和問題解決了 – Sarroura 2011-05-11 11:09:42

+5

使用System.ComponentModel.DataAnnotations.Schema; – Trevor 2013-04-17 00:11:24