I have a Submission controller that has one to many relationship to few other tables. Below is my model:
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; }
}
I want the application to delete all child records when I delete a Submission record. Below is my delete method:
[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");
}
This gives me an error after the first iteration of the foreach loop. Below is the error I get:
Exception Details: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
How do I delete the child records in this case?