首页 > 解决方案 > MVC 5 - 尝试使用 linq 删除一行时,没有错误并且该行没有被删除。为什么?

问题描述

我尝试了许多不同的方法来删除IncidentDescriptionsDBContext 的一些行,但我真的无法弄清楚这一点。在调试窗口中,有一个 ID 和一个打印出来的描述从这一行显示,所以我知道有一行被选中,这不是问题:

foreach (var desc in DB.IncidentDescriptions.Where(d => d.AccidentHeaderId == supervisor.AccidentHeaderId)) {
    System.Diagnostics.Debug.WriteLine(desc.Id + " " + desc.Description);
}

控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = @"Id,AccidentHeaderId,DateLastModified,LastModifiedUsername,DateAccidentReported,EmployeeReported,ReportedInSameShift
,DateReportedOutsideShift,AccidentLocation,IncidentDate,IncidentTime,MedicalAttention,Clinic,ReturnToWork,DrugScreenPapers,DamageDesc,MissDollarEst,ActsContributed
,CorrectiveActions,DiscusedWithEmployee,WorkOrderComplete,Comments,AccidentNarrative,FirstName,LastName,DrugTested,FirstNameReportedTo,LastNameReportedTo
,DateInvestigationStarted,TimeInvestigationStarted,DeptManager, HospitalName,
BodyPartXREF, EmployeesInvolved, IncidentDescriptions, InjuryDescriptionXREF, UnsafeActXREF, WitnessesInvolved
")] AccidentSupervisorViewModel supervisor, List<string> SelectedUnsafeActs, int? SelectedLocation, List<string>DescriptionUser, List<string>DescriptionPosition)
{
    if (ModelState.IsValid)
    {
        using (DB)
        {
            using (var contextTransaction = DB.Database.BeginTransaction())
            {
                try
                {
                foreach (var desc in DB.IncidentDescriptions.Where(d => d.AccidentHeaderId == supervisor.AccidentHeaderId)) {
                    System.Diagnostics.Debug.WriteLine(desc.Id + " " + desc.Description);
                }
                DB.IncidentDescriptions.Remove(DB.IncidentDescriptions.FirstOrDefault(d => d.AccidentHeaderId == supervisor.AccidentHeaderId));
                DB.SaveChanges();
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    contextTransaction.Rollback();
                }
            }
        }
        return RedirectToAction("Index", "Incident"); 
    }
    return View(supervisor);
}

标签: asp.net-mvcentity-frameworklinq

解决方案


你没有提交你的交易。顺便说一句,EF 已经实现了工作单元,所以这可能是矫枉过正。此外,我会将 FirstOrDefault() 替换为 Single() - 如果找不到任何内容,则需要异常。另外,不确定您是否需要绑定。由于您有一个视图模型,因此只传递了这些值。

我会将正文重写为:

{
    if (ModelState.IsValid)
    {
        using (DB)
        {
            foreach (var desc in DB.IncidentDescriptions.Where(d => d.AccidentHeaderId == supervisor.AccidentHeaderId)) 
            {
                System.Diagnostics.Debug.WriteLine(desc.Id + " " + desc.Description);
            }
            DB.IncidentDescriptions.Remove(DB.IncidentDescriptions.Single(d => d.AccidentHeaderId == supervisor.AccidentHeaderId));
            DB.SaveChanges();
        }
        return RedirectToAction("Index", "Incident"); 
    }
    return View(supervisor);
}

推荐阅读