Composite Key with EF 4.1 Code First

前端 未结 2 1413
独厮守ぢ
独厮守ぢ 2020-11-29 19:50

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 th

相关标签:
2条回答
  • 2020-11-29 20:07

    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 });
    
    0 讨论(0)
  • 2020-11-29 20:22

    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; }
    
    }
    
    0 讨论(0)
提交回复
热议问题