首页 新闻 会员 周边

EF 组合主键报错,无法确定组合排序,请使用 ColumnAttribute

0
悬赏园豆:10 [已关闭问题] 关闭于 2016-05-02 17:57

在我的系统中员工表是用的两个字段做为主键,编译都没有报错,但运行是报无法确定组合排序,详细的错误见下图;按照错误提示给出的URL,看了官方文档,官方给出的说明如下面代码:

Composite keys

Entity Framework supports composite keys - primary keys that consist of more than one property. For example, your could have a Passport class whose primary key is a combination of PassportNumber and IssuingCountry.

public class Passport 

    [Key] 
    public int PassportNumber { get; set; } 
    [Key] 
    public string IssuingCountry { get; set; } 
    public DateTime Issued { get; set; } 
    public DateTime Expires { get; set; } 
}

If you were to try and use the above class in your EF model you wuld get an InvalidOperationExceptions stating;

Unable to determine composite primary key ordering for type 'Passport'. Use the ColumnAttribute or the HasKey method to specify an order for composite primary keys.

When you have composite keys, Entity Framework requires you to define an order of the key properties. You can do this using the Column annotation to specify an order.

Note: The order value is relative (rather than index based) so any values can be used. For example, 100 and 200 would be acceptable in place of 1 and 2.

public class Passport 

    [Key] 
    [Column(Order=1)] 
    public int PassportNumber { get; set; } 
    [Key] 
    [Column(Order = 2)] 
    public string IssuingCountry { get; set; } 
    public DateTime Issued { get; set; } 
    public DateTime Expires { get; set; } 
}


但是按要求添加[Column(Order=1)]后,找不到命名空间,在网上搜到有两个,一个在linq.mapping,一个在micrsoft.share.linq下面
但这两个都不行,真蛋疼,请大神指教,如何处理!
错误页面提示:

“/”应用程序中的服务器错误。


 

无法确定类型“Models.wygl_office_Employee”的组合主键排序。请使用 ColumnAttribute (请参阅 http://go.microsoft.com/fwlink/?LinkId=386388)或 HasKey (请参阅 http://go.microsoft.com/fwlink/?LinkId=386387)方法指定组合主键的顺序。

 说明: 执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 

异常详细信息: System.InvalidOperationException: 无法确定类型“Models.wygl_office_Employee”的组合主键排序。请使用 ColumnAttribute (请参阅 http://go.microsoft.com/fwlink/?LinkId=386388)或 HasKey (请参阅 http://go.microsoft.com/fwlink/?LinkId=386387)方法指定组合主键的顺序。

源错误:

beggar_的主页 beggar_ | 初学一级 | 园豆:10
提问于:2016-05-02 17:50
< >
分享
所有回答(2)
0

采用的在mapping中设置,具体的如下  this.HasKey(t => new { t.PrecinctID ,t.EmployeeID});

将两个主键采用new 的方式定义就可以了

beggar_ | 园豆:10 (初学一级) | 2016-05-02 17:57
0

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Business_attrib2object>().HasKey(ba => new { ba.IdClass, ba.IdAttribute });
}

HelloLLLLL | 园豆:434 (菜鸟二级) | 2022-10-30 22:44
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册