'How to Specify a Compound key in Entity Framework Code First

I have a quick question about setting up the mappings between [Order Details], [Products] and [Orders] in the Northwind datbase.

[Order Details] has no primary key, and looks like this

[Order Details]
OrderId (int)
ProductId (int)
...

So my question is how do I (and can I) set up my OrderDetails class to work like this?

public class OrderDetails
{
    public virtual Order Order { get; set; }
    public virtual Product Product { get; set; }
    public Decimal UnitPrice { get; set; }
    public int Quantity { get; set; }
    public Decimal Discount { get; set; }
}

My data context looks like this

public class NorthwindDb : DbContext
{
    public DbSet<Product> Products { get; set; }
    public DbSet<Category> Categories { get; set; }
    public DbSet<Order> Orders { get; set; }
    public DbSet<OrderDetails> OrderDetails { get; set; }
    public DbSet<Customer> Customers { get; set; }


    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new OrderDetailsConfiguration());
    }

    public static void InitializeBecauseOfThatWeirdMetaDataThingThatIDontUnderstandYet()
    {
        Database.SetInitializer<NorthwindDb>(null);
    }

}

And My OrderDetailsConfiguration (empty because I don't know what I'm doing)

public class OrderDetailsConfiguration : EntityConfiguration<OrderDetails>
{
    public OrderDetailsConfiguration()
    {
        //HasKey(x => x.Order.OrderId);
        //HasKey(x => x.Product.ProductId);
    }
}

Any hints or ideas would be great.



Solution 1:[1]

Mark key fields with [Key] attribute. You will need to add [Column(Order = x)] in case of compound keys, x = 0, 1, 2, ... Numbering can start from any number https://msdn.microsoft.com/en-us/data/jj591583.aspx

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user1920925