更新 EF Core 记录时发生 ThrowAggregateUpdateConcurrencyExceptionAsync 错误 - 如何解决?

问题描述 投票:0回答:0

我目前正在使用 Entity Framework Core 开发一个项目,我在更新与另一个模型具有一对多关系的模型时遇到了问题。具体来说,当我尝试更新具有 Prescription_OPD_Medications 列表的 Prescription_OPD 模型时,我收到异常抛出消息“Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ThrowAggregateUpdateConcurrencyExceptionAsync”。

public async Task<Prescription_OPD?> Update(Guid id, UpdatePrescriptionOPDRequest updatePrescription_OPDRequest)
        {
            var existingPrescription_OPD = await dbContext.Prescriptions_OPD.Include(p => p.prescriptionMedications).FirstOrDefaultAsync(p => p.Id == id);
            if (existingPrescription_OPD != null)
            {
                existingPrescription_OPD.Date = updatePrescription_OPDRequest.Date;
                existingPrescription_OPD.Note = updatePrescription_OPDRequest.Note;
                existingPrescription_OPD.StartDate = updatePrescription_OPDRequest.StartDate;
                existingPrescription_OPD.EndDate = updatePrescription_OPDRequest.EndDate;
                existingPrescription_OPD.NoOfDates = updatePrescription_OPDRequest.NoOfDates;
                existingPrescription_OPD.Refills = updatePrescription_OPDRequest.Refills;

                dbContext.Prescription_OPD_Medications.RemoveRange(existingPrescription_OPD.prescriptionMedications);
                existingPrescription_OPD.prescriptionMedications = new List<Prescription_OPD_Medications>();
                foreach (var medication in updatePrescription_OPDRequest.Medications)
                {
                    existingPrescription_OPD.prescriptionMedications.Add(new Prescription_OPD_Medications()
                    {
                        Id = Guid.NewGuid(),
                        PrescriptionId = existingPrescription_OPD.PrescriptionId,
                        MedicationName = medication.MedicationName,
                        Dosage = medication.Dosage,
                        Frequency = medication.Frequency
                    });
                }

                await dbContext.SaveChangesAsync();

                return existingPrescription_OPD;
            }

            return null;
        }

我试过调试代码,当我尝试删除现有的处方药列表并根据请求中的更新数据用新列表替换它时,似乎会出现问题。但是,我不确定如何解决这个问题。

任何帮助或指导将不胜感激。提前谢谢你!

entity-framework http exception asp.net-web-api one-to-many
© www.soinside.com 2019 - 2024. All rights reserved.