105

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.

Majid
  • 13,853
  • 15
  • 77
  • 113
bugnuker
  • 3,918
  • 7
  • 24
  • 31

2 Answers2

185

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

}
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
105

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 });
taylonr
  • 10,732
  • 5
  • 37
  • 66
  • this does work, but I am hoping for an annotation that works. There were samples with CTP 4 but these no longer work in 4.1 RC – bugnuker Mar 29 '11 at 15:11
  • 3
    I know you were looking for annotations, but thought this might help in the search... like I said we're not using annotations so I wasn't much help there...hope you find the answer – taylonr Mar 29 '11 at 15:15
  • 14
    I like this approach. Keeps the model clean of Context concerns. Thx. – ctorx Feb 03 '12 at 20:31
  • Does somebody know whether setting composite primary key using fluent api works for SQL CE? It doesn't work for me (gives an error that 'EntityType ... has no key defined') and I'm not sure to create a new question or not. – kasitan Sep 05 '13 at 16:04
  • If you mock your DbContext for unit testing purpose, how do you make sure the modelBuilder is executed in order to define the relationship between entities and/or composite primary keys? – Jim Aho Aug 19 '14 at 12:38