0

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?

Jasen
  • 14,030
  • 3
  • 51
  • 68
Eric
  • 3,165
  • 1
  • 19
  • 25
  • See [here](http://stackoverflow.com/questions/16654828/how-to-remove-child-one-to-many-related-records-in-ef-code-first-database). You can also configure cascade deletions instead of deleting all children first. See [here](http://stackoverflow.com/questions/5614485/deleting-multiple-records-for-a-related-table), and [here](http://stackoverflow.com/questions/5448702/cascading-deletes-with-entity-framework-related-entities-deleted-by-ef), and ... – Jasen Apr 07 '16 at 17:48
  • This has nothing to do with child related records. you will get the same problem if you weren't using EF. you are modifying a collection whilst you are iterating it. this is not permitted. you need to use a for loop and go backwards removing the item from the collection or if possible just do a RemoveAll from the collection! – Ahmed ilyas Apr 07 '16 at 17:51

1 Answers1

0

I do not enable the On Delete Cascade, but I modified the foreach loop and it works

foreach (var w in db.WorkorderLogs.Where(x => x.SubmissionId == submission.Id))
{
    db.WorkorderLogs.Remove(w);
}
Eric
  • 3,165
  • 1
  • 19
  • 25