Creating Composite Keys using Code First with Entity Framework


When creating, 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 OrderId { get; set; }
        [Key, Column(Order = 2)]
        public int ProductId { get; set; }
        [RelatedTo(ForeignKey = " OrderId ")]
        public Order Orderlist { get; set; }
        [RelatedTo(ForeignKey = "TrackId")]
        public Product Productlist{ 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 OrderId { get; set; }
        public int ProductId { get; set; }     
        [RelatedTo(ForeignKey = " OrderId ")]
        public Order Orderlist { get; set; }
        [RelatedTo(ForeignKey = "TrackId")]
        public Product Productlist{ get; set; }


    }

And the composite key is defined using the HasKey method when building the model:
var builder = new ModelBuilder();
    builder.Entity< Orderlist >().HasKey(p=>new {p.OrderId, p.productId});
    model = builder.CreateModel();

No comments:

Post a Comment