当我尝试在数据库中插入记录时,收到以下错误消息:
INSERT语句与FOREIGN KEY约束冲突 “FK_dbo.Order_dbo.AspNetUsers_UserId”。冲突发生在 数据库“Test”,表“dbo.AspNetUsers”,列“Id”。该 声明已被终止。
免责声明:我知道之前已经问过这个问题(here,here和here),但没有一个答案帮我修复了这个错误。< / em>的
以下是模型:
[Table("Order")]
public class Order
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity), Key]
public int Id { get; set; }
[Required]
public string UserId { get; set; }
public virtual List<OrderDetails> OrderDetails { get; set; }
[ForeignKey("UserId")]
public virtual ApplicationUser User { get; set; }
}
[Table("OrderDetails")]
public class OrderDetails
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity), Key]
public int Id { get; set; }
[Required]
public int OrderId { get; set; }
[ForeignKey("OrderId")]
public virtual Order Order { get; set; }
}
public class ApplicationUser : IdentityUser
{
[MaxLength(15)]
public string FirstName { get; set; }
[MaxLength(15)]
public string LastName { get; set; }
[MaxLength(50)]
public string EmailAddress { get; set; }
public virtual List<Order> Orders { get; set; }
}
插入新Order
的代码:
public OrderDetails Add(dynamic addOrderDetails, string userId)
{
if (addOrderDetails.OrderId == null)
{
var order = new Order()
{
UserId = userId,
CreateDate = DateTime.Now,
Status = OStatus.InProgress,
Confirmed = (DateTime?)null,
};
var newOrder = _dbContext.Orders.Add(order);
_dbContext.Entry(order).State = EntityState.Added;
_dbContext.SaveChanges(); // this is where the error msg is being thrown.
var orderDetails = new OrderDetails()
{
OrderId = newOrder.Id,
ServiceId = addOrderDetails.ServiceId,
EventStart = start,
EventEnd = end
};
var newOrderDetails = _dbContext.OrderDetails.Add(orderDetails);
_dbContext.Entry(orderDetails).State = EntityState.Added;
_dbContext.SaveChanges();
}
return null;
}
此行正在抛出错误:_dbContext.SaveChanges(); // this is where the error msg is being thrown.
调试时我可以看到UserId = userId,
有值。
那么为什么我收到此错误消息?
答案 0 :(得分:8)
数据库中的AspNetUsers
表必须包含一个记录,其UserId
列具有您在新订单中使用userId
设置的值。 Order.UserId
不仅是必需的,还是AspNetUsers
表的外键(请参阅[ForeignKey("UserId")]
中的Order
属性)。因此,Order.UserId
具有任何值(!= null)是不够的,它必须具有与AspNetUsers
表中的记录对应的值。
该异常意味着AspNetUsers
表中没有此类记录。