gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:37:27 25 4
gpt4 key购买 nike

当我试图在数据库中插入一条记录时,我得到这个错误信息:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Order_dbo.AspNetUsers_UserId". The conflict occurred in database "Test", table "dbo.AspNetUsers", column 'Id'. The statement has been terminated.

免责声明:我知道之前有人问过这个问题(hereherehere),但没有一个答案能帮助我解决这个错误。

模型如下:

[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();//这是抛出错误信息的地方。

调试时我可以看到 UserId = userId, 有一个值。

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

最佳答案

AspNetUsers数据库中的表必须包含一条记录,其 UserId列具有您使用 userId 设置的值在新秩序中。 Order.UserId不仅是必需的,而且还是 AspNetUsers 的外键表(参见 [ForeignKey("UserId")] 中的 Order 属性)。所以,Order.UserId 还不够有任何 值 (!= null),它必须有一个对应于 AspNetUsers 中的记录的值表。

异常意味着 AspNetUsers 中不存在这样的记录表。

关于c# - EF Code First INSERT 语句与 FOREIGN KEY 约束冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21881644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com