Revert database context to previous state EF Core 7

35 views Asked by At

I'm working on a console app to migrate a large number of data from Sharepoint to a SQL Server database.

I have a database context and, inside if, a for loop of some items from Sharepoint. For every item I have a transaction so the final code is something like this:

using (ExampleContext db = new ExampleContext())
{
    List<Item> sharepointItems = Installer_Service.SharepointItems();     
    // this has some parameters but it's irrelevant
    for (int d = 0; d < sharepointItems.Count; d++)
    { 
        using (var tran = db.Database.BeginTransaction())
        {
            try
            {
                // the whole code
                db.SaveChanges();
                tran.Commit();
            }
            catch (Exception ex) 
            {
                tran.Rollback();
                continue;
            }
        }
    }
}

Assuming that sharepointItems.Count = 4, I start to loop. The first item goes smoothly.

The second item catches with some exception. With "continue" I can go on to the third item of the loop. When I try to save the third item, though, I still have the context with the exception of the previous item so the third one also catches, even if there's nothing wrong with it.

I'm looping a list that could contain a million items so opening a context for each one would kill the database (SQL Server).

Is there a way to do something like the tran.Rollback but with the context? Saving the current context state at the beginning of every loop and then restore it in case it catches?

0

There are 0 answers