EF 4.1代码优先的复合密钥

我试图找出如何有一个复合键使用 EF 代码第一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; }


}

我需要“活动名称”也是一个关键。 当然,我可以围绕这个编写代码,但这不是很好的数据库设计。

51920 次浏览

We don't use the annotations, instead we override the model builder, in which case you can do something like:

modelBuilder.Entity<Activity>().HasKey(a => new { a.ActivityId, a.ActivityName });

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; }


}