Entity Framework 6 losing connection on long transaction

c# entity-framework entity-framework-6 sql-server

Question

I'm currently doing a complex migration task where each iteration must be wrapped in a transaction in case of failure. Each iteration can take as long as 2 hours.

This has mostly been successful. There have been some cases where a long operation is required in between accesses to the connection.

Essentially the connection is idle for a while (> 10 minutes) and when I try to use the connection again I discover it is broken:

System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.Data.SqlClient.SqlException: The connection is broken and recovery is not possible.  The connection is marked by the server as unrecoverable.  No attempt was made to restore the connection.
   at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__180_0(Task`1 result)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()

The code looks something like:

// Context = instance of DbContext
using (var dbContextTransaction = Context.Database.BeginTransaction())
{
    DoStuffWithContext(Context);

    PotentiallyLongOperationWithoutContext();

    DoMoreStuffWithContext(Context);
}

Normally this all works fine but when PotentiallyLongOperationWithoutContext does take a long time I get the exception when DoMoreStuffWithContext first tries to use the context.

1
1
1/23/2019 5:09:28 PM

Popular Answer

One thing is not clear from your post what are using ? Code first or Db First ? However you should dispose your DbContext resources after all your transaction happens and definitely implement this line of code in your DbConetext constructor

 public partial class RDSS_WBEntities : DbContext
    {
        public RDSS_WBEntities() : base("name=RDSS_WBEntities")
        {
            this.Database.CommandTimeout = int.MaxValue;
        }
    }
0
2/1/2019 4:37:42 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow