Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework; How to handle an exception in foreach loop and keep iterating

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.

How can I appropriately catch the exception and undo or clear the failed DeleteObject request so that subsequent deletes can be performed.

public ActionResult Delete(int[] ListData)
{
    List<int> removed = new List<int>();
    List<int> error = new List<int>();
    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 > 0)
    {
        return Json(new { Success = false, Removed = removed, Error = error });
    }
    return Json(new { Success = true, Removed = removed });
}

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.

I am using Entity Framework 4.

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.

like image 201
SidewaysGravity Avatar asked May 23 '12 14:05

SidewaysGravity


People also ask

How do you handle exceptions in parallel foreach?

For and Parallel. ForEach overloads do not have any special mechanism to handle exceptions that might be thrown. In this respect, they resemble regular for and foreach loops ( For and For Each in Visual Basic); an unhandled exception causes the loop to terminate as soon as all currently running iterations finish.

How do you handle a loop exception?

Output. One way to execute the loop without breaking is to move the code that causes the exception to another method that handles the exception. If you have try catch within the loop it gets executed completely inspite of exceptions.

How do you continue in parallel foreach?

When you converted your loop into a compatible definition for the Parallel. Foreach logic, you ended up making the statement body a lambda. Well, that is an action that gets called by the Parallel function. So, replace continue with return , and break with Stop() or Break() statements.

How to break out of a foreach loop c#?

At any point within the body of an iteration statement, you can break out of the loop by using the break statement, or step to the next iteration in the loop by using the continue statement.


1 Answers

I assume that the the same context, this.DB, is being used in this.getValidObject(id) to retrieve an entity. If that is the case, in the exception block call: this.DB.detach(deleteme). That should prevent the SaveChanges() to try to delete the problematic entity on the next iteration.

like image 136
Umair Ishaq Avatar answered Oct 26 '22 18:10

Umair Ishaq