I’m wrote an insert method that uses linq and loops through 2 lists, the first being able to go up to 14k objects and the send about 8k objects.
Whenever I run this method, I always get “Transaction Timeout Exception”. Can you help me improve this?
public void InsertNewInventoryGoodsEvents(List<GoodsEvent> eventsList, List<InventoryGoods> goodsList)
{
InventoryGoodsEvents ige = new InventoryGoodsEvents();
TransactionScope scope= new TransactionScope();
int i = 0;
const int batchSize = 50; // or even 50
foreach (InventoryGoods good in goodsList)
{
if (i == 50)
{
if (scope != null)
{
context.SubmitChanges();
}
i = 0;
}
try
{
foreach (GoodsEvent g in eventsList)
{
if (g.Gid == good.Gid)
{
ige = new InventoryGoodsEvents() { EventId = g.Id, InventoryGood = good.Id };
context.InventoryGoodsEvents.InsertOnSubmit(ige);
}
}
}
catch (Exception ex)
{
ex.ToString();
}
++i;
}
if (scope != null)
{
context.SubmitChanges();
scope.Complete();
}
}
the Foreach in a foreach can can be re-written as this-
Then you can insert these however you’d like. It looks like you’re doing batches of 50 right now? You can continue that if you’d like… This will take all of the work outside of the transaction scope though, so you can probably lob the whole bit in there at once, if your results aren’t too huge.