question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Mapping exceptions after an incident where a lot of database calls were made (without recovering)

See original GitHub issue

Describe what is not working as expected.

There was an incident on our production environment. We have two instances of the same application (backend). A client made around 2.5k requests at the same time (1.25k / app).

The first issue which appeared is the following exception:

System.Data.Entity.Core.EntityException: The underlying provider failed on Open.
 ---> System.InvalidOperationException: Timeout expired.  The timeout period elapsed prior to obtaining a connection from the pool.  This may have occurred because all pooled connections were in use and max pool size was reached.
   at async System.Data.Common.ADP.ExceptionWithStackTrace(Exception e)

   at async System.Data.Entity.Infrastructure.DbExecutionStrategy.<>c__DisplayClass19_0.<<ExecuteAsync>b__0>d.MoveNext()

   at System.Data.Entity.Infrastructure.DbExecutionStrategy.ProtectedExecuteAsync<TResult>(Func<T> operation, CancellationToken cancellationToken)
   at System.Data.Entity.Core.EntityClient.EntityConnection.OpenAsync(CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at System.Data.Entity.Core.EntityClient.EntityConnection.OpenAsync(CancellationToken cancellationToken)
   at System.Data.Entity.Core.Objects.ObjectContext.EnsureConnectionAsync(Boolean shouldMonitorTransactions, CancellationToken cancellationToken)
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransactionAsync<T>(Func<T> func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess, CancellationToken cancellationToken)
   at System.Data.Entity.Utilities.TaskExtensions.CultureAwaiter<T>.GetResult()
   at System.Data.Entity.Infrastructure.DbExecutionStrategy.ProtectedExecuteAsync<TResult>(Func<T> operation, CancellationToken cancellationToken)
   at System.Data.Entity.Utilities.TaskExtensions.CultureAwaiter<T>.GetResult()
   at System.Data.Entity.Core.Objects.ObjectQuery<T>.GetResultsAsync(Nullable<T> forMergeOption, IDbExecutionStrategy executionStrategy, CancellationToken cancellationToken)
   at System.Data.Entity.Utilities.TaskExtensions.CultureAwaiter<T>.GetResult()
   at System.Data.Entity.Internal.LazyAsyncEnumerator<T>.FirstMoveNextAsync(CancellationToken cancellationToken)
   at System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions.ForEachAsync<T>(IDbAsyncEnumerator<T> enumerator, Action<T> action, CancellationToken cancellationToken)

that is expected taking into consideration the number of concurrent HTTP requests. After that our both applications started throwing a lot of random exceptions as you can see in the following picture:

image Those exceptions do not make any sense. I even saw two exceptions for the same property: once trying to map it into a boolean, and second time trying to map it into a decimal (instead of string). It feels like Entity Framework cannot map the retrieved data into correct data types. Seems like everything is scrambled. The major problem is that it does not recover. The incident lasted around 30-40 minutes and a simple recreation of the pod fixed it.

I will paste some stacktraces below:

System.InvalidOperationException: The 'x' property on 'y' could not be set to a 'System.String' value. You must set this property to a non-null value of type 'System.Int32'. 
   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader<T>.GetValue(DbDataReader reader, Int32 ordinal)
   at lambda_method(Closure , Shaper )
   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly<TEntity>(Func<T1,T2> constructEntityDelegate, EntityKey entityKey, EntitySet entitySet)
   at lambda_method(Closure , Shaper )
   at System.Data.Entity.Core.Common.Internal.Materialization.Coordinator<T>.ReadNextElement(Shaper shaper)
   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper<T>.SimpleEnumerator.MoveNextAsync(CancellationToken cancellationToken)
   at System.Data.Entity.Internal.LazyAsyncEnumerator<T>.FirstMoveNextAsync(CancellationToken cancellationToken)
   at System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions.FirstOrDefaultAsync<TSource>(IDbAsyncEnumerable<T> source, CancellationToken cancellationToken)
System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.Data.SqlClient.SqlDataReader.CheckHeaderIsReady(Int32 columnIndex, Boolean permitAsync, String methodName)
   at System.Data.SqlClient.SqlDataReader.IsDBNull(Int32 i)
   at lambda_method(Closure , Shaper )
   at System.Data.Entity.Core.Common.Internal.Materialization.Coordinator.HasNextElement(Shaper shaper)
   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper<T>.RowNestedResultEnumerator.MaterializeRow()
   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper<T>.RowNestedResultEnumerator.MoveNext()
   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper<T>.ObjectQueryNestedEnumerator.TryReadToNextElement()
   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper<T>.ObjectQueryNestedEnumerator.MoveNext()
   at System.Collections.Generic.List<T>..ctor(IEnumerable<T> collection)
   at System.Linq.Enumerable.ToList<TSource>(IEnumerable<T> source)
System.InvalidOperationException: The specified cast from a materialized 'System.String' type to the 'System.Int32' type is not valid.
   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader<T>.GetValue(DbDataReader reader, Int32 ordinal)
   at lambda_method(Closure , Shaper )
   at System.Data.Entity.Core.Common.Internal.Materialization.Coordinator<T>.ReadNextElement(Shaper shaper)
   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper<T>.SimpleEnumerator.MoveNextAsync(CancellationToken cancellationToken)
   at System.Data.Entity.Internal.LazyAsyncEnumerator<T>.FirstMoveNextAsync(CancellationToken cancellationToken)
   at System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions.FirstOrDefaultAsync<TSource>(IDbAsyncEnumerable<T> source, CancellationToken cancellationToken)

Useful information

Our context:

public partial class XEntities : DbContext
{
        public XEntities() : base("name=Entities")
        {
    		Database.SetInitializer<XEntities>(null);
        }
    
    	public XEntities(string connectionName) : base(connectionName)
        {
    		Database.SetInitializer<XEntities>(null);
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
                XModelKeyBuilder.BuildCompositeKeys(modelBuilder); 
        }
       //dbsets...
}

DatabaseFactory:

public class DatabaseFactory : Disposable, IDatabaseFactory
  {
    private DbContext dataContext;
    public DbContext Get()
    {
      if (dataContext != null) return dataContext;
      dataContext = new XEntities(connString);
      dataContext.Configuration.UseDatabaseNullSemantics = true;

      return dataContext;
    }
    protected override void DisposeCore()
    {
      if (dataContext != null)
        dataContext.Dispose();
    }
  }

Unfortunately, we use another layer above EF: Generic Repository & UoW Patterns where we inject into constructor the IDatabaseFactory. We use Microsoft.Extensions.DependencyInjection.Abstractions 3.1.2 for DI. The registrations are Scoped. We use async all the way down.

People with same problem:

https://stackoverflow.com/questions/50560257/entity-framework-throws-unexpected-exceptions-with-a-heavy-workload https://stackoverflow.com/questions/35896100/strange-error-in-sql-server-from-asp-net-app https://stackoverflow.com/questions/47076273/getting-exception-suddenly-from-entityframework https://stackoverflow.com/questions/41839754/entity-framework-6-1-3-invalidoperationexception-after-a-few-days-of-running https://stackoverflow.com/questions/35011086/ef-randomly-sees-wrong-property-type

Further technical details

  • ASP.NET Core 3.1
  • EF 6.4 (database first)
  • Kubernetes 1.16.7 (AKS)
  • Docker image - aspnet:3.1-alpine
  • Azure SQL (Standard S3: 100 DTUs)

I have a .NET Framework project with the EDMX. After I generate the entities, I run a powershell script to move them to the .NET Standard 2.1 project.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:1
  • Comments:14 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
florinciubotariucommented, Sep 4, 2020

@jdaigle The incident appeared again this morning.

To keep it straight-forward, the client apps made A LOT of requests to our APIs - APIs which are hitting big database tables.

We have 3 pods for our app. Out of a sudden a lot of timeouts started appearing and since the client apps did not block the UI, it didn’t stop making requests to our apps and forced us to continue hitting our database. That basically means we got no chance of recovering because the client apps didn’t allow us to. When this happens, in order to speed up the recovery, I killed 2/3 pods (in order to create other 2) and the timeouts are starting to disappear (since I get rid of our scheduled DB calls - caused mainly by the triggered API calls)

The weird thing is that the issue we discussed in this thread appeared only on a newly created pod (one of the two):

pod memory usage You can see in the screenshot the lifetime of our pod. When I saw exceptions flooding I immediately logged the stdout to a log file and killed it.

I’ve ended up scaling the Azure SQL from S3 to S4 and everything is fine now.

I created a timeline showing the Apdex score (all 3 pods combined) during the incident: incident-04 09 2020

In the following 2 screenshots you can see the metrics of the pod which threw mapping exceptions: pod-1 pod-2

What I found out:

  1. Not all requests were affected - some of them worked fine (they took a lot of time to respond because of the database but eventually they did).
  2. Two new types of weird exception were logged:
System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details.
 ---> System.Data.SqlClient.SqlException (0x80131904): The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION.
   at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__126_0(Task`1 result)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location where exception was thrown ---
   at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommandsAsync(EntityCommand entityCommand, CommandBehavior behavior, CancellationToken cancellationToken)
ClientConnectionId:x
Error Number:3903,State:2,Class:16
ClientConnectionId before routing:x
Routing Destination:x
   --- End of inner exception stack trace ---
   at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommandsAsync(EntityCommand entityCommand, CommandBehavior behavior, CancellationToken cancellationToken)
   at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.ExecuteAsync[TResultType](ObjectContext context, ObjectParameterCollection parameterValues, CancellationToken cancellationToken)
   at System.Data.Entity.Utilities.TaskExtensions.CultureAwaiter`1.GetResult()
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransactionAsync[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess, CancellationToken cancellationToken)
   at System.Data.Entity.Utilities.TaskExtensions.CultureAwaiter`1.GetResult()
   at System.Data.Entity.Infrastructure.DbExecutionStrategy.ProtectedExecuteAsync[TResult](Func`1 operation, CancellationToken cancellationToken)
   at System.Data.Entity.Utilities.TaskExtensions.CultureAwaiter`1.GetResult()
   at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResultsAsync(Nullable`1 forMergeOption, IDbExecutionStrategy executionStrategy, CancellationToken cancellationToken)
   at System.Data.Entity.Utilities.TaskExtensions.CultureAwaiter`1.GetResult()
   at System.Data.Entity.Internal.LazyAsyncEnumerator`1.FirstMoveNextAsync(CancellationToken cancellationToken)
   at System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions.FirstOrDefaultAsync[TSource](IDbAsyncEnumerable`1 source, CancellationToken cancellationToken)
System.Data.Entity.Infrastructure.CommitFailedException: An error was reported while committing a database transaction but it could not be determined whether the transaction succeeded or failed on the database server. See the inner exception and http://go.microsoft.com/fwlink/?LinkId=313468 for more information.
 ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Data.SqlClient.SqlInternalTransaction.GetServerTransactionLevel()
   at System.Data.SqlClient.SqlInternalTransaction.CheckTransactionLevelAndZombie()
   at System.Data.SqlClient.SqlInternalTransaction.Commit()
   at System.Data.SqlClient.SqlTransaction.Commit()
   at System.Data.Entity.Infrastructure.Interception.DbTransactionDispatcher.<>c.<Commit>b__6_0(DbTransaction t, DbTransactionInterceptionContext c)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   --- End of inner exception stack trace ---
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbTransactionDispatcher.Commit(DbTransaction transaction, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Core.EntityClient.EntityTransaction.Commit()
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransactionAsync[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess, CancellationToken cancellationToken)
   at System.Data.Entity.Utilities.TaskExtensions.CultureAwaiter`1.GetResult()
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStoreAsync(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, CancellationToken cancellationToken)
   at System.Data.Entity.Infrastructure.DbExecutionStrategy.ProtectedExecuteAsync[TResult](Func`1 operation, CancellationToken cancellationToken)
   at System.Data.Entity.Utilities.TaskExtensions.CultureAwaiter`1.GetResult()
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternalAsync(SaveOptions options, Boolean executeInExistingTransaction, CancellationToken cancellationToken)
1reaction
jdaiglecommented, Aug 25, 2020

I would like to contribute my experience with what I think is the exact same issue (which I’ve never found a the root cause or resolved):

I’ve been seeing these exceptions in our production systems for nearly 3 years. Early on, these exceptions happened frequently in clusters. Sometimes the cluster would last for 5 minutes, sometimes up to 30 minutes. It almost always affects just a single server/instance at a time.

In the past 3 years, the occurrence rate of these exceptions has gone down dramatically. It’s just a small “blip” and Users rarely notice since things recover quickly. However just yesterday (August 24 2020) we encountered a cluster of these exceptions affected 1/3 of our production servers over a period of 30-40 minutes. It was bad enough that Users noticed this time - from their perspective the system was down since so many things were crashing.

Usually this problem eventually resolves itself after a few minutes. It’s almost as if some/most of the connections in the connection pool are corrupt or in some bad state? And after a while the connection pool clears itself out.

Some notes about application code:

  • Most of our data access uses Entity Framework. There’s a decent mix of older non-async code paths and newer async code paths.
  • We do a fair amount of hand written SQL executing using Dapper with connections from the same connection pool. This has increased over the past 3 years, but usage was minimal when these exceptions started 3 years ago.
  • Most calls to SaveChanges or SaveChangesAsync() are not scoped in an explicit local transaction. But some are (maybe 10%). And some use TransactionScope (maybe 0.5%).
  • We cannot reproduce these errors. There’s nothing we can do to trigger them, and we’ve never been able to reproduce these exceptions (even trying to write intentionally buggy code).
  • Unlike @florinciubotariu, we’ve not been able to observe any specific exception that occurs prior.

Technical Details

  • Entity Framework 6.2.0 (but we’ve observed this on every version since 6.1.2)
  • .NET Framework 4.8 (but we’ve observed this on every version since 4.6.2)
  • IIS on Windows Server 2016
  • SQL Server 2016 SP (but we’ve observed this on older version of SQL Server as well)

Exceptions/Stack Trace Sample

Below is sample of the types of exceptions we see. We’ll often see dozens or hundreds of these exceptions. They all for different queries, different entities. Some async code, some non-async code.

System.InvalidOperationException: The 'x' property on 'y' could not be set to a 'System.Int32' value. You must set this property to a non-null value of type 'System.Guid'.
    System.Data.Entity.Core.Common.Internal.Materialization.Shaper+ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal):104
    (unknown).lambda_method(Closure , Shaper ):-1
    System.Data.Entity.Core.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet):196
    (unknown).lambda_method(Closure , Shaper ):-1
    System.Data.Entity.Core.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper):114
    System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1+SimpleEnumerator.MoveNext():39
    System.Collections.Generic.List`1..ctor(IEnumerable`1 collection):119
    System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source):20

System.InvalidOperationException: The specified cast from a materialized 'System.String' type to the 'System.Guid' type is not valid.
    System.Data.Entity.Core.Common.Internal.Materialization.Shaper+ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal):104
    (unknown).lambda_method(Closure , Shaper ):-1
    System.Data.Entity.Core.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper):114
    System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1+SimpleEnumerator.MoveNext():39
    System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source):48

System.InvalidCastException: Specified cast is not valid.
    System.Data.SqlClient.SqlBuffer.get_SqlGuid():22
    System.Data.SqlClient.SqlDataReader.GetGuid(Int32 i):9
    (unknown).lambda_method(Closure , Shaper ):-1
    System.Data.Entity.Core.Common.Internal.Materialization.Coordinator.HasNextElement(Shaper shaper):47
    System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1+RowNestedResultEnumerator.MaterializeRow():52
    System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1+RowNestedResultEnumerator.MoveNext():45
    System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1+ObjectQueryNestedEnumerator.TryReadToNextElement():19
    System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1+ObjectQueryNestedEnumerator.MoveNext():7
    System.Collections.Generic.List`1..ctor(IEnumerable`1 collection):119
    System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source):20

System.InvalidOperationException: The specified cast from a materialized 'System.Boolean' type to the 'System.Guid' type is not valid.
    System.Data.Entity.Core.Common.Internal.Materialization.Shaper+ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal):104
    (unknown).lambda_method(Closure , Shaper ):-1
    System.Data.Entity.Core.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper):114
    System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1+SimpleEnumerator.MoveNext():39
    System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source):65
    System.Data.Entity.Internal.Linq.InternalSet`1.FindInStore(WrappedEntityKey key, String keyValuesParamName):10
    System.Data.Entity.Internal.Linq.InternalSet`1.Find(Object[] keyValues):68

System.IndexOutOfRangeException: Index was outside the bounds of the array.
    System.Data.SqlClient.SqlDataReader.CheckHeaderIsReady(Int32 columnIndex, Boolean permitAsync, String methodName)
    System.Data.SqlClient.SqlDataReader.IsDBNull(Int32 i):58
    System.Data.Entity.Core.Common.Internal.Materialization.Shaper+ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal) 
    (unknown).lambda_method(Closure , Shaper ):-1
    System.Data.Entity.Core.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet):196
    (unknown).lambda_method(Closure , Shaper ):-1
    System.Data.Entity.Core.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper):114
    System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1+SimpleEnumerator.MoveNext():39
    System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source):65
    System.Data.Entity.Internal.Linq.InternalSet`1.FindInStore(WrappedEntityKey key, String keyValuesParamName):10
    System.Data.Entity.Internal.Linq.InternalSet`1.Find(Object[] keyValues):68

System.IndexOutOfRangeException: Index was outside the bounds of the array.
    System.Data.SqlClient.SqlDataReader.CheckHeaderIsReady(Int32 columnIndex, Boolean permitAsync, String methodName)
    System.Data.SqlClient.SqlDataReader.IsDBNull(Int32 i):58
    System.Data.Entity.Core.Common.Internal.Materialization.Shaper+ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal)
    (unknown).lambda_method(Closure , Shaper ):-1
    System.Data.Entity.Core.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper):114
    System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1+SimpleEnumerator+<MoveNextAsync>d__4.MoveNext():196
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw():12
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task):40
    System.Data.Entity.Internal.LazyAsyncEnumerator`1+<FirstMoveNextAsync>d__0.MoveNext():311
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw():12
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task):40
    System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions+<ForEachAsync>d__5`1.MoveNext():178
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw():12
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task):40
    System.Runtime.CompilerServices.TaskAwaiter`1.GetResult():11

System.IndexOutOfRangeException: Index was outside the bounds of the array.
    System.Data.SqlClient.SqlDataReader.CheckHeaderIsReady(Int32 columnIndex, Boolean permitAsync, String methodName)
    System.Data.SqlClient.SqlDataReader.IsDBNull(Int32 i):58
    (unknown).lambda_method(Closure , Shaper ):-1
    System.Data.Entity.Core.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper):114
    System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1+SimpleEnumerator.MoveNext():39
    System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source):65

We also have some transaction-related errors in the mix. Some of these exceptions are particularly weird because they’re being thrown from queries which aren’t being executed in any sort of transaction (no local transaction, no TransactionScope). We do have code that uses local transactions, and we do use TransactionScope in a few specific places.

System.Data.SqlClient.SqlException: New request is not allowed to start because it should come with valid transaction descriptor.
    System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction):94
    System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose):380
    System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
    System.Data.SqlClient.SqlDataReader.TryConsumeMetaData():64
    System.Data.SqlClient.SqlDataReader.get_MetaData():60
    System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted):243
    System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest):1627
    System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry):632
    System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method):25
    System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method):103
    System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed):241
    System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext):114
    System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior):10

System.InvalidOperationException: ExecuteReader requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized.
    System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async):377
    System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry):51
    System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method):25
    System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method):80
    System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed):241
    System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext):114
    System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior):10
    System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior):41
    System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues):309
    System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess):138
    System.Data.Entity.Core.Objects.ObjectQuery`1+<>c__DisplayClass7.<GetResults>b__5():28
    System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation):54
    System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption):165
    System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
    System.Data.Entity.Internal.LazyEnumerator`1.MoveNext():8
    System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source):65
    System.Data.Entity.Internal.Linq.InternalSet`1.FindInStore(WrappedEntityKey key, String keyValuesParamName):10
    System.Data.Entity.Internal.Linq.InternalSet`1.Find(Object[] keyValues):68

System.Data.SqlClient.SqlException: The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION.
    System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction):94
    System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose):380
    System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
    System.Data.SqlClient.SqlDataReader.TryConsumeMetaData():64
    System.Data.SqlClient.SqlDataReader.get_MetaData():60
    System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted):243
    System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest):1627
    System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry):632
    System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method):25
    System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method):103
    System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed):241
    System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext):114
    System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior):10
    System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior):41
    System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues):309
    System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess):138
    System.Data.Entity.Core.Objects.ObjectQuery`1+<>c__DisplayClass7.<GetResults>b__5():28
    System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation):54
    System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption):165
    System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
    System.Data.Entity.Internal.LazyEnumerator`1.MoveNext():8
    System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source):65
    System.Data.Entity.Internal.Linq.InternalSet`1.FindInStore(WrappedEntityKey key, String keyValuesParamName):10
    System.Data.Entity.Internal.Linq.InternalSet`1.Find(Object[] keyValues):68

System.Data.SqlClient.SqlException: New transaction is not allowed because there are other threads running in the session.
    System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction):94
    System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose):380
    System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
    System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj):32
    System.Data.SqlClient.TdsParser.TdsExecuteTransactionManagerRequest(Byte[] buffer, TransactionManagerRequestType request, String transactionName, TransactionManagerIsolationLevel isoLevel, Int32 timeout, SqlInternalTransaction transaction, TdsParserStateObject stateObj, Boolean isDelegateControlRequest):568
    System.Data.SqlClient.SqlInternalConnectionTds.ExecuteTransactionYukon(TransactionRequest transactionRequest, String transactionName, IsolationLevel iso, SqlInternalTransaction internalTransaction, Boolean isDelegateControlRequest):384
    System.Data.SqlClient.SqlInternalConnection.BeginSqlTransaction(IsolationLevel iso, String transactionName, Boolean shouldReconnect):134
    System.Data.SqlClient.SqlConnection.BeginTransaction(IsolationLevel iso, String transactionName)
    System.Data.SqlClient.SqlConnection.BeginDbTransaction(IsolationLevel isolationLevel)
    System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed):241
    System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.BeginTransaction(DbConnection connection, BeginTransactionInterceptionContext interceptionContext):114
    System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation):54
    System.Data.Entity.Core.EntityClient.EntityConnection.BeginDbTransaction(IsolationLevel isolationLevel):163
    System.Data.Entity.Core.EntityClient.EntityConnection.BeginDbTransaction(IsolationLevel isolationLevel):194
    System.Data.Entity.Core.EntityClient.EntityConnection.BeginTransaction(IsolationLevel isolationLevel)
    System.Data.Entity.DbContextTransaction..ctor(EntityConnection connection, IsolationLevel isolationLevel):19
    System.Data.Entity.Database.BeginTransaction(IsolationLevel isolationLevel):30

System.Data.SqlClient.SqlException: The server failed to resume the transaction. Desc:13e000000da.
    System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction):94
    System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose):380
    System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
    System.Data.SqlClient.SqlDataReader.TryConsumeMetaData():64
    System.Data.SqlClient.SqlDataReader.get_MetaData():60
    System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted):243
    System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest):1627
    System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry):632
    System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method):25
    System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method):103
    System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed):241
    System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext):114
    System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior):10
Read more comments on GitHub >

github_iconTop Results From Across the Web

Best Practices for exceptions - .NET
Learn best practices for exceptions, such as using try/catch/finally, handling common conditions without exceptions, and using predefined .
Read more >
How to solve 8 common Elasticsearch errors and exceptions
Common Elasticsearch errors and exceptions and how to avoid them! Including best practices to help identify, minimize, and handle ES issues.
Read more >
Exceptions pertaining to data access
Many stale connection exceptions are caused by intermittent problems with the network of the database server. Obtaining a new connection and retrying the ......
Read more >
Exceptions and debugging - Advanced R. - Hadley Wickham
Debugging, condition handling, and defensive programming. What happens when something goes wrong with your R code? What do you do? What tools do...
Read more >
SqlException cause all subsequent db call to fail with same ...
I have an application on ASP.NET Core 2.2 and using Entity Framework Core 2.2.6. ... Microsoft.EntityFrameworkCore.DbUpdateException: An error ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found