I am starting using the Entity Framework CTP 4, that includes code first approach with data annotations.
When creating composite primary keys, you need specify the order of the primary keys, otherwise you will get an exception similar to:
System.InvalidOperationException : Unable to determine composite primary key ordering for type 'PlaylistTrack'. Use the ColumnAttribute or the HasKey method to specify an order for composite primary keys.
As the exception message describes, one option is to use data annotations and add the Key and Column attributes to define the composite key as shown below:
public class PlaylistTrack { [Key, Column(Order=1)] public int PlaylistId { get; set; } [Key, Column(Order = 2)] public int TrackId { get; set; } [RelatedTo(ForeignKey = "PlaylistId")] public Playlist Playlist { get; set; } [RelatedTo(ForeignKey = "TrackId")] public Track Track { get; set; } }
Another option is to define the composite key using the HasKey method. In this option, the entity class will be:
public class PlaylistTrack { public int PlaylistId { get; set; } public int TrackId { get; set; } [RelatedTo(ForeignKey = "PlaylistId")] public Playlist Playlist { get; set; } [RelatedTo(ForeignKey = "TrackId")] public Track Track { get; set; } }
And the composite key is defined using the HasKey method when building the model:
var builder = new ModelBuilder(); //... builder.Entity<PlaylistTrack>().HasKey(p=>new {p.PlaylistId, p.TrackId}); //... model = builder.CreateModel();
My personal choice is to use data annotations which were introduced since EF4 CTP3.