title: Entity Framework; How to handle an exception in foreach loop and keep iterating
body: <p>When I iterate through a foreach with the following code it successfully catches the first exception that occurs and adds the id to my error list. On all the subsequent iterations of the loop, it will continue to catch the previous exception.</p>
  
  <p>How can I appropriately catch the exception and undo or clear the failed DeleteObject request so that subsequent deletes can be performed. </p>
  
  <pre><code>public ActionResult Delete(int[] ListData)
  {
      List&lt;int&gt; removed = new List&lt;int&gt;();
      List&lt;int&gt; error = new List&lt;int&gt;();
      Item deleteMe;
      foreach (var id in ListData)
      {
          deleteMe = this.getValidObject(id);
          if (deleteMe == null)
          {
              error.Add(id);
              continue;
          }
  
          try
          {
              this.DB.Items.DeleteObject(deleteMe);
              this.DB.SaveChanges();
              removed.Add(id);
          }
          catch (DataException ex)
          {
              // revert change to this.DB.Items?
              error.Add(id);
          }
      }
      if (error.Count &gt; 0)
      {
          return Json(new { Success = false, Removed = removed, Error = error });
      }
      return Json(new { Success = true, Removed = removed });
  }
  </code></pre>
  
  <p>I have searched SO and google and most people will process all the delete objects first and then save changes so that it is one transaction. But I need it to process each transaction individually so a single failure does not stop the rest of the transactions.</p>
  
  <p>I am using Entity Framework 4.</p>
  
  <p>The exception I get for this specific example caused by foreign keys being associated to the item that is being removed. While in production I will be handling this scenario, it should be able to continue on no matter what the exception is.</p>