How to specify a composite key in Entity First root code

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

[Order Details] does not have a primary key and looks as follows

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

So my question is: how do I (and can I) configure my class OrderDetailsto work as follows?

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 is as follows

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 Mine 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 tips or ideas would be great.

+3
source share
2 answers

First, you will need to explicitly put PK and FK inside the OrderDetails class:

public class OrderDetails 
{        
    public int OrderID { get; set; }
    public int ProductID { get; set; }

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

PK OrderDetailsConfiguration:
( , Northwind OrderID ProductID PK OrderDetails).

public class OrderDetailsConfiguration : EntityConfiguration<OrderDetails> 
{
    public OrderDetailsConfiguration() 
    {
        HasKey(od => new 
        {
            od.ProductID,
            od.OrderID
        });
    }
}

RecreateDatabaseIfModelChanges, , :

Database.SetInitializer<NorthwindDb>(
        new RecreateDatabaseIfModelChanges<NorthwindDb>());

, EF FK OrderDetails " " OrderID ProductID :

First , <navigation property name><primary key property name> (.. ProductProductID), <principal class name><primary key property name> (.. ProductProductID) <primary key property name> (.. ProductID) , , . , , . .

+4

[Key]. [Column (Order = x)] , x = 0, 1, 2,... https://msdn.microsoft.com/en-us/data/jj591583.aspx

+1

Source: https://habr.com/ru/post/1774389/


All Articles