EF Code First INSERT语句与FOREIGN KEY约束冲突

时间:2014-02-19 13:16:29

标签: c# ef-code-first runtime-error entity-framework-6 asp.net-identity

当我尝试在数据库中插入记录时,收到以下错误消息:

  

INSERT语句与FOREIGN KEY约束冲突   “FK_dbo.Order_dbo.AspNetUsers_UserId”。冲突发生在   数据库“Test”,表“dbo.AspNetUsers”,列“Id”。该   声明已被终止。

免责声明:我知道之前已经问过这个问题(hereherehere),但没有一个答案帮我修复了这个错误。< / 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,有值。

那么为什么我收到此错误消息?

1 个答案:

答案 0 :(得分:8)

数据库中的AspNetUsers表必须包含一个记录,其UserId列具有您在新订单中使用userId设置的值。 Order.UserId不仅是必需的,还是AspNetUsers表的外键(请参阅[ForeignKey("UserId")]中的Order属性)。因此,Order.UserId具有任何值(!= null)是不够的,它必须具有与AspNetUsers表中的记录对应的值。

该异常意味着AspNetUsers表中没有此类记录。