Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
876 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 Reply

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...