Composite Key with EF 4.1 Code First
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; }
}
我们不使用注释,而是重写模型构建器,在这种情况下,您可以执行如下操作:
modelBuilder.Entity<Activity>().HasKey(a => new { a.ActivityId, a.ActivityName });
链接地址: http://www.djcxy.com/p/90208.html
上一篇: 在代码第一个实体框架中手动编辑数据库
下一篇: EF 4.1代码优先的复合钥匙