2011-05-11 76 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