Search code examples
c#entity-frameworkentity-framework-6.1

Batch saving ef 6 records in a for loop


Does any one know or explain why the following code throws the following errors mention below while using EF6? I am getting these errors intermittently. Also, please suggest on how to save records when an error occurs.

using (var context = GetNewDBEntities())
{
   for (var i = 0; i < Docs.Count; i++)
   {
      context.Docs.Add(Docs[i]);

      //Save 50 Records per batch
      if (i % 50 == 0)
          context.SaveChanges();
   }
  context.SaveChanges();
}

EF 6 drops connection for the above code with the following errors.

  1. An error occurred while updating the entries.
  2. The request failed to run because the batch is aborted, this can be caused by abort signal sent from client, or another request is running in the same session, which makes the session busy. A severe error occurred on the current command. The results, if any, should be discarded.
  3. Failed to establish a MARS session in preparation to send the request to the server. (provider: SMux Provider, error: 19 - Physical connection is not usable)

Solution

  • I included SqlAzureExecutionStrategy into EF6.1 and the errors dissapeared, atleast for 2 weeks without errors now.