Handling SaveChanges Exceptions in a Loop

There are several conditions in Entity Framework that are processed at the database level and passed back to EF as exceptions in Context.SaveChanges ().

If you are creating new objects in a loop, you can handle the exception through the "Try Catch" building block, but how do you clear the problematic entity from the SaveChanges () queue?

For example (moving SaveChanges outside of the loop has no positive effect, so it is shown here in the loop):

while(i < 1000)
{
    MyEntity Wibble = new MyEntity();
    Wibble.Name = "Test " + i.ToString();

    Context.AddToTests(Wibble);
    Context.SaveChanges();

}

      

If for some reason there is already a Wibble that causes the insert to fail at a unique constraint in the database, then I can handle the immediate exception in a loop.

However, on the next iteration, it fails again because the problematic Wibble instance still exists in the SaveChanges queue - how are you supposed to handle this?

You can of course check ahead of time if we are creating a duplicate Wibble, but this results in two back trips to the database. I don't mind handling the exception, I just want you to be aware of this issue, please ignore this post and move on to it.

Thoughts? Am I doing it wrong?

EDIT:

I solved the immediate problem, but only when you execute Context.SaveChanges () in a loop. If you just call SaveChanges () once, outside of the loop, my solution doesn't work - can anyone suggest an alternative method that will work?

+2


source to share


1 answer


As usual, I decided to ask someone within 15 minutes :)

The solution is to remove the object object from the ObjectStateManager when handling the exception, allowing the loop to continue:



while(i < 1000)
{
    MyEntity Wibble = new MyEntity();
    Wibble.Name = "Test " + i.ToString();

    Context.AddToTests(Wibble);

    try
    {
        Context.SaveChanges();
    }
    catch
    {
        Context.ObjectStateManager.GetObjectStateEntry(Wibble).Delete();
    }

}

      

+2


source







All Articles