简体   繁体   English

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

[英]EF Code First The INSERT statement conflicted with the FOREIGN KEY constraint

When I try to insert a record in the database, I get this error message:当我尝试在数据库中插入一条记录时,我收到以下错误消息:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Order_dbo.AspNetUsers_UserId". INSERT 语句与 FOREIGN KEY 约束“FK_dbo.Order_dbo.AspNetUsers_UserId”冲突。 The conflict occurred in database "Test", table "dbo.AspNetUsers", column 'Id'.冲突发生在数据库“Test”、表“dbo.AspNetUsers”、“Id”列中。 The statement has been terminated.该语句已终止。

Disclaimer: I know that this question has been asked before ( here , here and here ), but none of answers helped me fix this error I get.免责声明:我知道这个问题之前已经被问过( 这里这里这里),但没有一个答案能帮助我解决这个错误。

Here are the models:以下是模型:

[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; }
}

Code that inserts the new Order :插入新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;
}

The error is being thrown at this line: _dbContext.SaveChanges(); // this is where the error msg is being thrown.此行引发错误: _dbContext.SaveChanges(); // this is where the error msg is being thrown. _dbContext.SaveChanges(); // this is where the error msg is being thrown.

When debugging I can see that UserId = userId, has a value.调试时我可以看到UserId = userId,有一个值。

So why am I getting this error message?那么为什么我会收到此错误消息?

The AspNetUsers table in the database must contain a record whose UserId column has the value you set with userId in the new order. 数据库中的AspNetUsers表必须包含一条记录,其UserId列具有您在新订单中使用userId设置的值。 Order.UserId is not only required but also a foreign key to the AspNetUsers table (see the [ForeignKey("UserId")] attribute in Order ). Order.UserId不仅是必需的,但也有外键AspNetUsers表(见[ForeignKey("UserId")]在属性Order )。 So, it's not enough that Order.UserId has any value (!= null), it must have a value that corresponds to a record in the AspNetUsers table. 因此, Order.UserId具有任何值(!= null)是不够的,它必须具有与AspNetUsers表中的记录对应的值。

The exception means that such a record is not present in the AspNetUsers table. 该异常意味着AspNetUsers表中不存在此类记录。

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Order_dbo.AspNetUsers_UserId". INSERT 语句与 FOREIGN KEY 约束“FK_dbo.Order_dbo.AspNetUsers_UserId”冲突。 The conflict occurred in database "Test", table "dbo.AspNetUsers", column 'Id'.冲突发生在数据库“Test”、表“dbo.AspNetUsers”、“Id”列中。 The statement has been terminated.该语句已终止。

This means that the individual order (row) at Order_dbo CANNOT be created without a reference to an existing user at AspNetUsers .这意味着在没有引用AspNetUsers的现有用户的情况下,无法创建Order_dbo的单个订单(行)。

This error is coming from the actual DB, that's why you're getting it when you reach _dbContext.SaveChanges() , and not before.这个错误来自实际的数据库,这就是为什么你在到达_dbContext.SaveChanges()时得到它,而不是之前。

Possible solution可能的解决方案

Make the column AspNetUsers_UserId nullable.使AspNetUsers_UserId列可以为空。

[Required]
public int? UserId { get; set; } 

I suggest you to use int instead of string type for you Id.我建议您为您的 ID 使用int而不是string类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 EF代码的第一个PK列-无法将值NULL插入列中/ INSERT语句与FOREIGN KEY约束冲突 - EF code first PK column - Cannot insert the value NULL into column / The INSERT statement conflicted with the FOREIGN KEY constraint SqlException: INSERT 语句与 FOREIGN KEY 约束冲突,首先使用 EF 代码 C# - SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint using EF code first C# In Code first INSERT 语句与 FOREIGN KEY 约束冲突 - In Code first The INSERT statement conflicted with the FOREIGN KEY constraint 实体框架代码第一个INSERT语句与FOREIGN KEY约束冲突 - Entity Framework code first INSERT statement conflicted with the FOREIGN KEY constraint 代码优先INSERT语句与FOREIGN KEY约束冲突 - Code first The INSERT statement conflicted with the FOREIGN KEY constraint EF Core:INSERT语句与FOREIGN KEY约束冲突 - EF Core: The INSERT statement conflicted with the FOREIGN KEY constraint INSERT语句与EF Core中的FOREIGN KEY约束冲突 - The INSERT statement conflicted with the FOREIGN KEY constraint in EF Core INSERT 语句首先与实体框架数据库中的 FOREIGN KEY 约束冲突 - The INSERT statement conflicted with the FOREIGN KEY constraint in Entity Framework database first INSERT语句与FOREIGN KEY约束冲突 - The INSERT statement conflicted with the FOREIGN KEY constraint BulkInsert:INSERT语句与FOREIGN KEY约束冲突 - BulkInsert: The INSERT statement conflicted with the FOREIGN KEY constraint
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM