Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
861 views
in Technique[技术] by (71.8m points)

dotnet EF Core batch statements continue execution statements after failed statement

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.

question from:https://stackoverflow.com/questions/65850549/dotnet-ef-core-batch-statements-continue-execution-statements-after-failed-state

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...