Исключение:
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();
}
Я пытаюсь обновить свою БД, чтобы добавить в нее новые заказы. Каждый заказ связан с ProductionLine и содержит его идентификатор, а затем ProductionLine. Я считаю, что это происходит, это то, что он пытается добавить в таблицу ProductionLine, но это должно быть только добавление таблицы заказов. Я не уверен, как заставить его редактировать только таблицу заказов.
Модели:
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; }
}
Решение:
Я не установил в свой список ProductionLine, который запрашивался в другом операторе using, значение без изменений. Установите его в неизменном виде, чтобы EF знала, что ему не нужно его обновлять, что означало, что он не пытался дублировать идентификаторы.