SQL Server Express 2008, Joins, and Timeout Expired Error Message

entity-framework join sql-server stored-procedures timeout

Question

I have a stored procedure that does quite a bit of joins. The query though runs pretty fast, around 3 seconds. I just cant figure out the below error poping up every once in a while. I event cache the document that uses this query for a minute so it doesnt get ran over and over. I am using Entity Framework 5, and my stored procedure is using a CTE to do the paging. Any clues or insight?

 System.Data.SqlClient.SqlException (0x80131904): Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception (0x80004005): The wait operation timed out
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`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& 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)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
   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()
   at System.Data.Objects.ObjectContext.ExecuteStoreQueryInternal[TElement](String commandText, String entitySetName, MergeOption mergeOption, Object[] parameters)
   at System.Data.Objects.ObjectContext.ExecuteStoreQuery[TElement](String commandText, Object[] parameters)
   at System.Data.Entity.Internal.InternalContext.ExecuteSqlQuery[TElement](String sql, Object[] parameters)
   at System.Data.Entity.Internal.InternalContext.ExecuteSqlQueryAsIEnumerable[TElement](String sql, Object[] parameters)
   at System.Data.Entity.Internal.InternalContext.ExecuteSqlQuery(Type elementType, String sql, Object[] parameters)
   at System.Data.Entity.Internal.InternalSqlNonSetQuery.GetEnumerator()
   at System.Data.Entity.Internal.InternalSqlQuery`1.GetEnumerator()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Tournaments.Data.Repositories.Games.GamesRepository.GetGamesPaged(IGamesCriteria criteria)

Entity Framework Method

 public PagedResult<GameComplex> GetGamesPaged(IGamesCriteria criteria)
        {
            var results = DataContext.Database.SqlQuery<GameComplex>("EXEC [Schema].[Database] @Page, @PageSize, @SortOrder, @SortDirection, @EventId, @DivisionId, @DivisionTeamId, @Date, @SearchToken, @MemberId",
                new SqlParameter("Page", criteria.Page),
                new SqlParameter("PageSize", criteria.PageSize),
                new SqlParameter("SortOrder", GetDataValue(criteria.SortOrder)), 
                new SqlParameter("SortDirection", GetDataValue(criteria.SortDirection)),
                new SqlParameter("EventId", GetDataValue(criteria.EventId)),
                new SqlParameter("DivisionTeamId", GetDataValue(criteria.DivisionTeamId)), 
                new SqlParameter("DivisionId", GetDataValue(criteria.DivisionId)), 
                new SqlParameter("Date", GetDataValue(criteria.Date)),
                new SqlParameter("SearchToken", GetDataValue(criteria.SearchToken)),
                new SqlParameter("MemberId", GetDataValue(criteria.MemberId))).ToList();

            return new PagedResult<GameComplex>
                       {
                           Page = criteria.Page,
                           PageSize = criteria.PageSize,
                           Total = results.Any(q => q != null) ? results.FirstOrDefault().Total : 0,
                           Results = results
                       };
        }

SQL Server Stored Procedure Parameter Signature

ALTER PROCEDURE [Schema].[Database]
    @Page INT = 1,
    @PageSize INT = 10,
    @SortOrder NVARCHAR(100) = 'Id',
    @SortDirection VARCHAR(4) = 'ASC',
    @EventId INT = NULL,
    @DivisionId INT = NULL,
    @DivisionTeamId INT = NULL,
    @Date DATETIME = NULL,
    @SearchToken NVARCHAR(100) = NULL,
    @MemberId INT = NULL
AS
1
0
5/20/2013 5:10:57 PM

Accepted Answer

You may need to adjust the COMMAND timeout.

See:

Set Command Timeout in entity framework 4.3

or

How to set CommandTimeout for DbContext?

EDIT

Command Timeout:

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.commandtimeout.aspx

Connection Timeout:

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectiontimeout.aspx

EDIT:

Another possible issue is "parameter sniffing".

http://blogs.msdn.com/b/queryoptteam/archive/2006/03/31/565991.aspx

So try one of the parameter sniffing workarounds:

ALTER PROCEDURE [Schema].[Database]
    @Page INT = 1,
    @PageSize INT = 10,
    @SortOrder NVARCHAR(100) = 'Id',
    @SortDirection VARCHAR(4) = 'ASC',
    @EventId INT = NULL,
    @DivisionId INT = NULL,
    @DivisionTeamId INT = NULL,
    @Date DATETIME = NULL,
    @SearchToken NVARCHAR(100) = NULL,
    @MemberId INT = NULL
AS

Declare @PageCopyOf int
Select @PageCopyOf = @Page


Declare @PageSizeCopyOf int
Select @PageSizeCopyOf = @PageSize

Declare @SortOrderCopyOf NVARCHAR(100)
Select @SortOrderCopyOf = @SortOrder

Declare @SortDirectionCopyOf VARCHAR(4) 
Select @SortDirectionCopyOf = @SortDirection

Declare @EventIdCopyOf int
Select @EventIdCopyOf = @EventId

Declare @DivisionIdCopyOf int
Select @DivisionIdCopyOf = @DivisionId 


Declare @DivisionTeamIdCopyOf int
Select @DivisionTeamIdCopyOf = @DivisionTeamId

Declare @DateCopyOf DATETIME
Select @DateCopyOf = @Date

Declare @SearchTokenCopyOf  NVARCHAR(100)
Select @SearchTokenCopyOf = @SearchToken

Declare @MemberIdCopyOf int
Select @MemberIdCopyOf = @MemberId

And then everything below this uses/consumes the @XXXXXCopyOf variable and NOT the original variable (name).

It's worth a try.

3
5/23/2017 11:59:05 AM

Popular Answer

Just a guess, but the query runs fast (3 seconds) only when it is cached. Otherwise, it takes a lot longer and exceeds your server timeout setting. Since System.Data.SqlClient is raising the exception, it is likely that the default timeout is only 15 seconds.

MSDN: "The default value is 15 seconds"

Alternatively, try the CommandTimeout property of the SQLCommand object, which defaults to 30 seconds.

CommandTimeout



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