EF 4.1 Code First 的复合密钥
我试图弄清楚如何使用 EF code First 4.1 RC 获得复合密钥。
目前,我正在使用 [Key] 数据注释,但我无法指定多个键。
如何指定复合键?
这是我的示例:
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; }
}
我也需要“ActivityName”作为密钥。 当然,我可以围绕这个编写代码,但这不是好的数据库设计。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
Key
注释标记ActivityID
和ActivityName
属性,也可以使用 @taylonr 所描述的 Fluent API。编辑:
这应该有效 - 使用注释定义的复合键需要显式的列顺序:
You can mark both
ActivityID
andActivityName
properties withKey
annotation or you can use fluent API as described by @taylonr.Edit:
This should work - composite key defined with annotations requires explicit column order:
我们不使用注释,而是覆盖模型构建器,在这种情况下,您可以执行以下操作:
We don't use the annotations, instead we override the model builder, in which case you can do something like: