asp.net-mvc - MVC 5 - 尝试使用 linq 删除一行时,没有错误并且该行没有被删除。为什么?
问题描述
我尝试了许多不同的方法来删除IncidentDescriptions
DBContext 的一些行,但我真的无法弄清楚这一点。在调试窗口中,有一个 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);
}
解决方案
你没有提交你的交易。顺便说一句,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);
}
推荐阅读
- javascript - 如何用参数和模板文字描述函数?
- android - android studio 中的 build.gradle 问题
- pyqt5 - PyQt5:为什么 self.sender() 返回基础对象而不是派生对象发送它
- php - 生成 Uuid 作为主键
- c# - 如何在 C# 中拆分文本并保留每个部分的位置
- java - 什么是 Sybase 类 com.sybase.jdbc3.jdbc.SybDriver 的等效 MSSQL 驱动程序?
- javascript - 将具有多个索引的项目分组到子数组中
- c# - 使用泛型解析 json 模型的转换器
- azure - 使用 $filter 消费使用返回不正确的结果
- objective-c - 如何将 HEXString (NSString) 转换为 ByteArray Objective-C