Composite Key with EF 4.1 Code First

眉间皱痕 提交于 2019-11-26 10:20:28

问题


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.


回答1:


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

}



回答2:


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


来源:https://stackoverflow.com/questions/5466374/composite-key-with-ef-4-1-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!