具有EF 4.1代码的复合键 [英] Composite Key with EF 4.1 Code First

查看:85
本文介绍了具有EF 4.1代码的复合键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如何使用EF代码的复合键First 4.1 RC。



目前,我使用[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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆