dotnet EF Core batch statements continue execution statements after failed statement

554 Views Asked by At

I'm developing a system that will fetch a huge amount of data from another system. I'm inserting this data as batches using EF Core 3.0. I'm looking on a way to continue executing other statements even if there is/are statement(s) with Exceptions. e.g: If im inserting 10 records in the database and the record number 3 have an error EF Core should prevent it from saving but continue on trying to save the remaining 7 records.

things I have tried:

Interceptors

I couldn't find a way to make the system to continue on CommandFailed function.

1

There are 1 best solutions below

0
Lacutah On

Instead of utilizing interceptors, consider running your updates in batches that'll remove invalid entries and re-try saving.

So for each "batch" of records you want to save:

bool isSaved = false;
do
{
    try
    {
        await context.SaveChangesAsync();
        isSaved = true;
    }
    catch (DbUpdateException ex)
    {
        foreach (var entry in ex.Entries)
            entry.State = EntityState.Detached; // Remove from context so won't try saving again.
    }
}
while (!isSaved);

Original Source: http://andreyzavadskiy.com/2016/09/22/ignoring-dbupdateexception-and-continue/