首页 > 解决方案 > 实体框架数据库更新

问题描述

例外:

  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 表。我不知道如何让它只编辑订单表。

楷模:

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 知道它不需要更新它,这意味着它不会尝试复制 ID。

标签: c#asp.net-mvcentity-framework

解决方案


实体框架插入每个带有已添加状态的记录。因此,由于插入,您的实体也具有相同的状态。

您可以使用 context.Entry(prodLines.Where(x => x.Id == prodLineID).FirstOrDefault()).State= EntityState.Unchanged 设置它的状态;

Unchanged:实体正在被上下文跟踪并存在于数据库中,其属性值与数据库中的值没有变化

您可以在实体状态和 SaveChanges中查看有关此行为的更多信息


推荐阅读