同步更新调用期间的乐观并发异常

时间:2019-05-31 20:00:47

标签: c# mysql entity-framework foreign-keys

我正在尝试修改发票实体上的单个布尔属性。
这是我的课程:

public class Invoice : SoftDeletableEntity, IIsActive
{
    public Invoice()
    {
        IsEditable = true;
    }

    [ForeignKey("Booking")]
    public int BookingId { get; set; }
    public Booking Booking { get; set; }
    [ForeignKey("Customer")]
    public int CustomerId { get; set; }
    public Customer Customer { get; set; }
    public string OurReference { get; set; }
    public string CustomerReference { get; set; }
    public DateTime InvoiceDate { get; set; }
    public string InvoiceNumber { get; set; }
    [ForeignKey("AccountInformation")]
    public int AccountInformationId { get; set; }
    public AccountInformation AccountInformation { get; set; }
    public string Summary { get; set; }
    public List<InvoiceInformation> ImportantInformation { get; set; }
    [ForeignKey("InvoiceItem")]
    public List<int> InvoiceItemIds { get; set; }
    public List<InvoiceLineItem> InvoiceLineItems { get; set; }

    [ForeignKey("InvoiceDocument")]
    public List<int> InvoiceDocumentIds { get; set; }
    public List<InvoiceDocument> InvoiceDocuments { get; set; }
    public string CreatedBy { get; set; }
    public string Terms { get; set; }
    public bool IsReversal { get; set; }
    public bool IsEditable { get; set; }
    public int? ParentInvoiceId { get; set; }
}

这些类将导出为格式化的PDF。该过程运行良好,然后我得到了这段代码,用于检查PDF是否正确构建,然后,如果导出成功,该代码会将发票设置为不可编辑,如下所示:

    var doc = pdf.CreateInvoicePdf(resultModel, user);
    var bytes = GetPdfBytes(doc);

    if (bytes != null)
    {
        result.IsEditable = false;
    }

    unitOfWork.Commit();

当我将其称为“ unitOfWork.Commit();”时我收到以下异常:

System.Data.Entity.Infrastructure.DbUpdateException: 'An error occurred while saving entities that do not expose foreign key properties for their relationships.  

内部异常:

Message "Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions."

最近添加的外键引用是CustomerId,但它与所有其他外键一样设置。我已经检查了数据库中所有外键实体的FK = 0,并且没有丢失的引用。另外,它还在我的本地计算机上运行,​​因此我确定该实体未被浏览器以外的其他源修改。

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

以下是可能导致此问题的一些可能原因:

  1. 您尝试使用主键Id == 0或另一个default值(Guid.Emptystring.Empty)更新实体。因此,请验证ID是否设置正确。
  2. 当您尝试创建新对象并告诉EF使用EntityState.Modified对其进行了修改时。然后它将抛出此错误,因为它在数据库中尚不存在。因此,尝试使用EntityState.Added
  3. 您尝试更新或删除行,但该行不存在。