views:

47

answers:

2

Is it possible to insert only 100 records at a time per transactionScope? I would like to do things that way to avoid timeouts on my application.

using(var scope = new TransactionScope())
{

foreach ( object x in list)

        {
          // doing insertOnSubmit here
        }

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

}

So I would like to insert only 100 or even 50 rows inside that transaction just to avoid timeouts.

+1  A: 

Sure. Just start a new transaction every 50-100 records. What is your exact problem?

codymanix
I begin the transaction before I begin the foreach iteration and I do all inserts inside the foreach. (the list being iterated can come to have up to 10000 objects or more)I just don't know how can I start a new transaction in this scope.
Hallaghan
You could create a new TransactionScope.
codymanix
+3  A: 

Something like this?

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();
   }
}
MPritch
There's something in your code that totally escaped me. When is i ever being changed? Thanks for helping me out.
Hallaghan
@Hallaghan: Doh. It wasn't! Fixed :)
MPritch
Thank you a lot, it's just what I needed! I love how we can learn so much on this website!
Hallaghan
@Hallaghan: No problem! Glad to help
MPritch
I guess you really mean `catch`, not `finally`.
Mark Hurd
@Mark Hurd: Not entirely. The intention was to emulate a using block and always dispose of the TransactionScope. My implementation was a little borked though! Have corrected
MPritch