具有EF 4.1代码的复合键 [英] Composite Key with EF 4.1 Code First
问题描述
目前,我使用[Key]数据注释,但是我不能指定多个键。
如何指定一个复合键?
这里是我的例子:
public class ActivityType
{
[Key]
public int ActivityID {得到;组; }
[必需(ErrorMessage =需要一个ActivityName)]
[StringLength(50,ErrorMessage =活动名称不能超过50个字符)]
public string ActivityName {get;组;
}
我需要ActivityName也是一个关键。
当然,我可以围绕这个代码进行编码,但这不是很好的数据库设计。
c $ c> ActivityID 和活动名称
属性与键
注释,或者您可以使用流畅的API如@taylonr所述。
编辑:
这应该工作 - 使用注释定义的复合键需要显式列订单:
public class ActivityType
{
[Key,Column(Order = 0)]
public int ActivityID {get;组; }
[Key,Column(Order = 1)]
[必需(ErrorMessage =需要一个ActivityName)]
[StringLength(50,ErrorMessage =活动名称不得超过50个字符)]
public string ActivityName {get;组; }
}
I am trying to figure out how to have a composite key using EF code First 4.1 RC.
Currently, I am using the [Key] Data Annotation, but I am unable to specify more than one key.
how would one specify a composite key?
Here is my Example:
public class ActivityType
{
[Key]
public int ActivityID { get; set; }
[Required(ErrorMessage = "A ActivityName is required")]
[StringLength(50, ErrorMessage = "Activity Name must not exceed 50 characters")]
public string ActivityName { get; set; }
}
I need the "ActivityName" to also be a key. Sure, I can code around this, but thats not good database design.
You can mark both ActivityID
and ActivityName
properties with Key
annotation or you can use fluent API as described by @taylonr.
Edit:
This should work - composite key defined with annotations requires explicit column order:
public class ActivityType
{
[Key, Column(Order = 0)]
public int ActivityID { get; set; }
[Key, Column(Order = 1)]
[Required(ErrorMessage = "A ActivityName is required")]
[StringLength(50, ErrorMessage = "Activity Name must not exceed 50 characters")]
public string ActivityName { get; set; }
}
这篇关于具有EF 4.1代码的复合键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!