Insert 100 records per transaction

Is it possible to insert only 100 records at a time per transaction? I would like to do so in order to avoid timeouts in my application.

using(var scope = new TransactionScope())
{

foreach ( object x in list)

        {
          // doing insertOnSubmit here
        }

context.SubmitChanges();
scope.Complete();

}

Therefore, I would like to insert only 100 or even 50 rows inside this transaction in order to avoid timeouts.

+3
source share
2 answers

Something like that?

TransactionScope scope;
bool committed = false;
int i = 0;
const int batchSize = 100; // or even 50

try
{
    foreach ( object x in list)
    {
        if (i % batchSize == 0)
        {
            if (scope != null)
            {
                scope.Commit();
                scope.Dispose();
                context.SubmitChanges();
            }
            scope = new TransactionScope();
        }

        // doing insertOnSubmit here
        ++i;
    }

    if (scope != null)
    {
        scope.Commit();
        context.SubmitChanges();
    }
}
finally
{
   if (scope != null) 
   {
       scope.Dispose();
   }
}
+3
source

Of course. Just start a new transaction every 50-100 records. What is your specific problem?

+1
source

Source: https://habr.com/ru/post/1755958/


All Articles