例外:
HResult=0x80131501
Message=An error occurred while updating the entries. See the inner exception for details.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at SQDCDashboard.Services.Services.WindowsOrderImporterService.ImportOrder(DateTime date) in C:\Users\ME\source\repos\SQDC Dashboard\SQDCDashboard\SQDCDashboard.Services\Services\WindowsOrderImporterService.cs:line 145
at SQDCDashboardOrderImporterTester.Program.Main(String[] args) in C:\Users\ME\source\repos\SQDC Dashboard\SQDCDashboard\SQDCDashboardOrderImporterTester\Program.cs:line 11
Inner Exception 1:
UpdateException: An error occurred while updating the entries. See the inner exception for details.
Inner Exception 2:
SqlException: Violation of PRIMARY KEY constraint 'PK_dbo.ProductionLines'. Cannot insert duplicate key in object 'dbo.ProductionLines'. The duplicate key value is (ceae2692-ed1d-4902-8e16-781aba577130).
The statement has been terminated.
码:
{
Order ord = new Order
{
//ID and CreatedAt are being auto generated
SerialNumber = serialNum,
UnitNumber = unitNum,
ProductionNumber = prodNum,
MaterialNumber = materialNum,
SalesNumber = salesNum,
Location = Core.Enums.Location.Start,
ProductionLineId = prodLineID, //Foreign Key
ProdLine = prodLines.Where(x => x.Id == prodLineID).FirstOrDefault()
};
context.Orders.Add(ord);
context.SaveChanges();
}
我正在尝试更新数据库以向其添加新订单。每个订单都链接到生产线,并包含其ID,然后是生产线。我相信这是正在发生的事情,是它正在尝试将其添加到ProductionLine表中,但只应添加Orders表。我不确定如何仅编辑Orders表。
楷模:
public class Order : BaseEntity
{
public string ProductionNumber { get; set; }
public string SalesNumber { get; set; }
public string MaterialNumber { get; set; }
public string SerialNumber { get; set; }
public string UnitNumber { get; set; }
public DateTime? CompletionDate { get; set; }
public Location Location { get; set; }
public string ProductionLineId { get; set; }
public ProductionLine ProdLine { get; set; }
}
public class ProductionLine : BaseEntity
{
public string Name { get; set; }
public double UPE { get; set; }
public string ComputerName { get; set; }
public bool ActiveLine { get; set; }
}
解:
我没有将在其他using语句中查询的ProductionLine列表设置为不变。将其设置为不变会让EF知道它不需要更新,这意味着它没有尝试重复ID。
实体框架插入具有添加状态的每个记录。因此,由于插入,您的实体也具有相同的状态。
您可以使用context.Entry(prodLines.Where(x => x.Id == prodLineID).FirstOrDefault())。State = EntityState.Unchanged设置状态。
不变:实体正在由上下文跟踪并且存在于数据库中,并且其属性值与数据库中的值未更改
您可以在“实体状态”和“保存更改”中查看有关此行为的更多信息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句