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.

2 Answers 2

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

}
1
  • 1
    Anyway to add unique constraints / indexes that are not really keys? Commented Nov 28, 2012 at 0:41
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 });
5
  • 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
    Commented Mar 29, 2011 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
    Commented Mar 29, 2011 at 15:15
  • 14
    I like this approach. Keeps the model clean of Context concerns. Thx.
    – ctorx
    Commented Feb 3, 2012 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
    Commented Sep 5, 2013 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
    Commented Aug 19, 2014 at 12:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.