0

In a long time transaction with entityframework I get this error: (The transaction works ok in shorter transactions )

Error type: System.Data.EntityException
Message:    The underlying provider failed on Open.
Stack-Trace:    at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) 
at System.Data.EntityClient.EntityConnection.Open() at System.Data.Objects.ObjectContext.EnsureConnection() 
at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options) 
at System.Data.Entity.Internal.InternalContext.SaveChanges() 
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges() 
at System.Data.Entity.DbContext.SaveChanges() 
at UtilidadATC.Controllers.MapeosAJEController.CargaMasivaImportacion() in D:\INT\UtilidadATC\UtilidadATC\Controllers\MapeosAJEController.cs:line 687

Here is the code:

using (var scope = new TransactionScope()) 
{ 
    try 
    { 
        db.Database.ExecuteSqlCommand("DELETE FROM AJE_MAPEO_FAMILIAS");

        foreach (AJE_MAPEO_FAMILIAS aje_mapeo_familias in listaMapeos)
        {
            db.AJE_MAPEO_FAMILIAS.Add(aje_mapeo_familias);
        }
        db.SaveChanges();

        scope.Complete();
   }
   catch (Exception)
   {
      throw; 
   }
} 

Any idea?

jz jz
  • 41
  • 1
  • 1
  • 4
  • Partition the database add operations. So if your `aje_mapeo_familias` contains 10000 records to be added, split that list in 10 equal length lists of 1000, and SaveChanges each 1000 operations. – nbokmans May 11 '18 at 08:12
  • I tried that but i get the same error after some of the partials SaveChanges – jz jz May 11 '18 at 08:17
  • Is there an inner exception? It sounds like you are timing out, in which case you can look here: https://stackoverflow.com/questions/12788972/set-database-timeout-in-entity-framework – Wurd May 11 '18 at 10:38
  • the inner expection is: InnerException = {"The operation is not valid for the state of the transaction."} – jz jz May 11 '18 at 12:09
  • I have tried with: ((IObjectContextAdapter)db).ObjectContext.CommandTimeout = 600; but i get the same error – jz jz May 11 '18 at 12:20

0 Answers0