Answer the question
In order to leave comments, you need to log in
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; }
}
protected override void OnModelCreating(DbModelBuilder _)
{
...
_.Entity<PriceInOrder>().HasKey(e => new {e.Order_Id, e.Price_Id});
...
}
public class UsersInPriceOrders
{
public string User_Id { get; set; }
public int Order_Id { get; set; }
public int Price_Id { get; set; }
}
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);
...
}
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 });
}
Referenced table 'dbo.PriceOrders' is missing primary or candidate keys that match the list of referenced columns in the foreign key
Answer the question
In order to leave comments, you need to log in
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 FRAMEWORKUse MS SSMS.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question