title: Entity Framework ExecuteStoreCommands Exception during FirstOrDefault method
body: <p>Occasionally, while debugging some older application code, we receive an exception.  </p>
  
  <p>This is the offending line of code:</p>
  
  <pre><code>XMLReferenceSequence lastXml = (from xml in _entities.XMLReferenceSequences
                                          where xml.ServiceId == aService.Id
                                          where xml.SourceTypeId == ETrainsSourceType.SOURCE_RAIL_XML
                                          orderby xml.ReferenceDateTime descending
                                          select xml).FirstOrDefault();
  </code></pre>
  
  <p>It should be noted that the code does work most of the time and this does happen rarely.  </p>
  
  <p>Any thoughts on how to solve this issue would be appreciated.  Was considering  reformatting the code to perhaps do a ToList() first before FirstOrDefault()?</p>
  
  <p>Stack trace of the exception:</p>
  
  <hr>
  
  <p>Error processing Rail record. :    at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
     at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
     at System.Data.Entity.Core.Objects.ObjectQuery<code>1.&lt;&gt;c__DisplayClass7.&lt;GetResults&gt;b__6()
     at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func</code>1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
     at System.Data.Entity.Core.Objects.ObjectQuery<code>1.&lt;&gt;c__DisplayClass7.&lt;GetResults&gt;b__5()
     at System.Data.Entity.Infrastructure.DbExecutionStrategy.Execute[TResult](Func</code>1 operation)
     at System.Data.Entity.Core.Objects.ObjectQuery<code>1.GetResults(Nullable</code>1 forMergeOption)
     at System.Data.Entity.Core.Objects.ObjectQuery<code>1.&lt;System.Collections.Generic.IEnumerable&lt;T&gt;.GetEnumerator&gt;b__0()
     at System.Data.Entity.Internal.LazyEnumerator</code>1.MoveNext()
     at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable<code>1 source)
     at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.&lt;GetElementFunction&gt;b__1[TResult](IEnumerable</code>1 sequence)
     at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable<code>1 query, Expression queryRoot)
     at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
     at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
     at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable</code>1 source)
     at CHO.ETrains.Business.ETrainsManager.MovementProcessingFromRailList(ETrainFeedDto aFeed) in F:\agent_work\4\s\CHO.ALL\Business\CHO.ETrains.Business\ETrainsManager.cs:line 1961
     at CHO.ETrains.Business.ETrainsManager.ProcessMessageOffServiceBus(ETrainFeedDto eTrainFeed, RequestDto req, HashSet`1&amp; changesDetected, String schemaDir) in F:\agent_work\4\s\CHO.ALL\Business\CHO.ETrains.Business\ETrainsManager.cs:line 379</p>
  
  <hr>
  
  <p>Received Xml message which could not be processed:System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Execution Timeout Expired.  The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception: The wait operation timed out
     --- End of inner exception stack trace ---
     at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action<code>1 wrapCloseInAction)
     at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action</code>1 wrapCloseInAction)
     at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
     at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean&amp; dataReady)
     at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
     at System.Data.SqlClient.SqlDataReader.get_MetaData()
     at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption)
     at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task&amp; task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
     at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource<code>1 completion, Int32 timeout, Task&amp; task, Boolean&amp; usedCache, Boolean asyncWrite, Boolean inRetry)
     at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
     at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
     at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
     at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
     at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.&lt;Reader&gt;b__c(DbCommand t, DbCommandInterceptionContext</code>1 c)
     at System.Data.Entity.Infrastructure.Interception.InternalDispatcher<code>1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func</code>3 operation, TInterceptionContext interceptionContext, Action<code>3 executing, Action</code>3 executed)
     at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
     at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
     at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
     at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
     --- End of inner exception stack trace ---
     at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
     at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
     at System.Data.Entity.Core.Objects.ObjectQuery<code>1.&lt;&gt;c__DisplayClass7.&lt;GetResults&gt;b__6()
     at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func</code>1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
     at System.Data.Entity.Core.Objects.ObjectQuery<code>1.&lt;&gt;c__DisplayClass7.&lt;GetResults&gt;b__5()
     at System.Data.Entity.Infrastructure.DbExecutionStrategy.Execute[TResult](Func</code>1 operation)
     at System.Data.Entity.Core.Objects.ObjectQuery<code>1.GetResults(Nullable</code>1 forMergeOption)
     at System.Data.Entity.Core.Objects.ObjectQuery<code>1.&lt;System.Collections.Generic.IEnumerable&lt;T&gt;.GetEnumerator&gt;b__0()
     at System.Data.Entity.Internal.LazyEnumerator</code>1.MoveNext()
     at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable<code>1 source)
     at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.&lt;GetElementFunction&gt;b__1[TResult](IEnumerable</code>1 sequence)
     at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable<code>1 query, Expression queryRoot)
     at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
     at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
     at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable</code>1 source)
     at CHO.ETrains.Business.ETrainsManager.MovementProcessingFromRailList(ETrainFeedDto aFeed) in F:\agent_work\4\s\CHO.ALL\Business\CHO.ETrains.Business\ETrainsManager.cs:line 1961
     at CHO.ETrains.Business.ETrainsManager.ProcessMessageOffServiceBus(ETrainFeedDto eTrainFeed, RequestDto req, HashSet`1&amp; changesDetected, String schemaDir) in F:\agent_work\4\s\CHO.ALL\Business\CHO.ETrains.Business\ETrainsManager.cs:line 393
     at CHO.WebJobs.xmlReceive.MessageProcessor.ProcessBrokeredMessage(BrokeredMessage msg) in F:\agent_work\4\s\CHO.WebJobs\CHO.WebJobs.xmlReceive\MessageProcessor.cs:line 102</p>