我正在使用mvc5和Entity Framework代码优先迁移 我试图播种表,但我收到此错误消息:
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_dbo.Orders_dbo.Users_UserId". The conflict occurred in database
"DbDemo.Models.DbbContext", table "dbo.Users", column 'Id'.
The statement has been terminated.
我知道它的说法是,在播种订单之前,数据必须已经在users表中存在,但是用户中的userid
是主键,因此我认为由于其identity = true,它会自动播种!那为什么会出现这个错误?
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string PhoneNum { get; set; }
public string Location { get; set; }
public string Type { get; set; }
}
public class Order
{
[Key]
[Column(Order = 1)]
public int Id { get; set; }
//ForeignKey from Items table for the composite key
[Key]
[Column(Order = 2)]
public int? ItemId { get; set; }
public Item Item { get; set; }
//ForeignKey from Users table
public int? UserId { get; set; }
public User User { get; set; }
public int Quantity { get; set; }
public int? TotalPrice { get; set; } //why did i put this field??!
}
这是用户种子迁移:
public partial class UsersSeed : DbMigration
{
public override void Up()
{
Sql("insert into Users (Name,Email,Password,PhoneNum,Location,Type) values ('Khaled Tahboub', 'khaledk.tahboub@gmail.com', 'abc@123', '0797504280', 'Amman', 'A')");
Sql("insert into Users (Name,Email,Password,PhoneNum,Location,Type) values ('Muath Mustafa', 'muathmustafa@gmail.com', 'abc@123', '0797504280', 'Amman', 'A')");
Sql("insert into Users (Name,Email,Password,PhoneNum,Location,Type) values ('John Doe', 'JohnDoe@gmail.com', 'abc@123', '0797504280', 'Amman', 'B')");
}
public override void Down()
{
}
}
这是订单种子迁移:
public partial class OrdersSeed : DbMigration
{
public override void Up()
{
Sql("insert into Orders (UserId, ItemId, Quantity) values (1, 1, 1)");
}
public override void Down()
{
}
}