我有一个提交控制器,与其他几个表有一对多的关系。以下是我的模特:
public partial class Submission
{
public Submission()
{
this.WorkorderLogs = new HashSet<WorkorderLog>();
}
public int Id { get; set; }
public int WorkOrderId { get; set; }
public int PartStagingId { get; set; }
public System.DateTime SubmissionDate { get; set; }
public virtual PartStaging PartStaging { get; set; }
public virtual WorkOrder WorkOrder { get; set; }
public virtual ICollection<WorkorderLog> WorkorderLogs { get; set; }
}
我希望应用程序在删除提交记录时删除所有子记录。以下是我的删除方法:
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Submission submission = db.Submissions.Find(id);
foreach (var w in submission.WorkorderLogs)
{
submission.WorkorderLogs.Remove(w);
}
db.Submissions.Remove(submission);
db.SaveChanges();
return RedirectToAction("Index");
}
这在foreach循环的第一次迭代后给出了一个错误。以下是我得到的错误:
Exception Details: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
在这种情况下如何删除子记录?
答案 0 :(得分:0)
我没有启用On Delete Cascade,但我修改了foreach循环并且它可以正常工作
foreach (var w in db.WorkorderLogs.Where(x => x.SubmissionId == submission.Id))
{
db.WorkorderLogs.Remove(w);
}