A
A
Andrew2017-03-12 17:29:09
Entity Framework
Andrew, 2017-03-12 17:29:09

How to use the composite key of one table as a foreign key to the composite key of another?

Used by Entity Framework 6, CodeFirst, MS SQL, Asp.Net MVC
There is a simple table, prices (for services) in orders

public class PriceInOrder
{
    public int Order_Id { get; set; }
    public int Price_Id { get; set; }
    public decimal Count { get; set; }
}

The first two fields are a composite key, as described in OnModelCreating
protected override void OnModelCreating(DbModelBuilder _)
{
    ...
    _.Entity<PriceInOrder>().HasKey(e => new {e.Order_Id, e.Price_Id});
    ...
}

Now it was required to add workers who are for each service in the order.
public class UsersInPriceOrders
{
    public string User_Id { get; set; }
    public int Order_Id { get; set; }
    public int Price_Id { get; set; }
}

and added a contact code
protected override void OnModelCreating(DbModelBuilder _)
{
...
_.Entity<UsersInPriceOrders>().HasKey(u => new {u.User_Id, u.Order_Id, u.Price_Id});
_.Entity<UsersInPriceOrders>()
    .HasRequired(u => u.User)
    .WithMany()
    .HasForeignKey(e => e.User_Id).WillCascadeOnDelete(false);

_.Entity<UsersInPriceOrders>()
   .HasRequired(u => u.PriceInOrder)
   .WithMany()
   .HasForeignKey(u => new {u.Order_Id, u.Price_Id}).WillCascadeOnDelete(false);
...
}

This migration came out of this
public override void Up()
{
    CreateTable(
        "dbo.UsersInPriceOrders",
         c => new
            {
                User_Id = c.String(nullable: false, maxLength: 128),
                Order_Id = c.Int(nullable: false),
                Price_Id = c.Int(nullable: false),
            })
        .PrimaryKey(t => new { t.User_Id, t.Order_Id, t.Price_Id })
        .ForeignKey("dbo.PriceOrders", t => new { t.Price_Id, t.Order_Id })
        .ForeignKey("dbo.AspNetUsers", t => t.User_Id)
        .Index(t => t.User_Id)
        .Index(t => new { t.Order_Id, t.Price_Id });         
}

The problem is that when rolling this migration, an error occurs
Referenced table 'dbo.PriceOrders' is missing primary or candidate keys that match the list of referenced columns in the foreign key

At the same time, the composite primary key in this table is
What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Tsvetkov, 2017-03-12
@tsklab

There is a composite primary key in this table. What am I doing wrong?
Don't use a composite key. [ID] [int] IDENTITY(1,1) NOT NULL is fine.
MICROSOFT SQL SERVER ENTITY FRAMEWORK
Use MS SSMS.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question