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.


Download how.to.specify.a.compound.key.in.entity.framework.code.first.zip
Direct Link


Download


Download how.to.specify.a.compound.key.in.entity.framework.code.first.zip
Mediafire


Download


Download how.to.specify.a.compound.key.in.entity.framework.code.first.zip
1Fichier


Download

Both comments and pings are currently closed.

Comments are closed.