I have the following query:
var trains = queryableTrains.Select(t => new TrainDto
{
Id = t.Id,
Prefix = t.Prefix,
Color = t.Color,
PlannedMovements = t.TrainMovementPlans
.Where(p => trackCircuitIds.Contains(p.TrackCircuitId) && p.TimeStamp >= start && p.TimeStamp <= end)
.Select(p => new TrainMovementDto
{
SgfId = null,
Prefix = t.Prefix,
BlockSectionId = p.TrackCircuit.TrackCircuitGroupId ?? p.TrackCircuitId,
Timestamp = p.TimeStamp,
IsExit = false
})
.GroupBy(o => o.BlockSectionId)
.Select(o => o.First())
//.OrderBy(d => d.Timestamp)
.ToList(),
// ...
It's a lot to code to share everything so I will share the concept hoping it helps.
Basically my data model is as follows:
Train has several PlannedMovements
I want to use GroupBy to remove "duplicates", i.e., movements that has the same BlockSectionId (after the projection).
When I run the above code, even with the OrderBy commented, I get the following exception:
[17:00:55 ERR] Failed executing DbCommand (9ms) [Parameters=[#_outer_Prefix='?' (Size = 4000), #__start_2='?' (DbType = DateTime2), #__end_3='?' (DbType = DateTime2), #_outer_Id2='?' (DbType = Int64)], CommandType='"Text"', CommandTimeout='30']
SELECT #_outer_Prefix AS [Prefix], COALESCE([p.TrackCircuit3].[YRCTCGID], [p5].[YSBTRCID]) AS [BlockSectionId], [p5].[YSBTIMES], CAST(0 AS bit) AS [IsExit], [p.TrackCircuit3].[YRCTCGID], [p5].[YSBTRCID]
FROM [YSBPLTMT] AS [p5]
INNER JOIN [YRCTRCIT] AS [p.TrackCircuit3] ON [p5].[YSBTRCID] = [p.TrackCircuit3].[YRCTRCID]
WHERE (([p5].[YSBTRCID] IN ( _HUGE_GROUP_I_HAVE_TO_CHANGE_FOR_A_JOIN_ ) AND ([p5].[YSBTIMES] >= #__start_2)) AND ([p5].[YSBTIMES] <= #__end_3)) AND (#_outer_Id2 = [p5].[YSBTRAID])
ORDER BY COALESCE([p.TrackCircuit3].[YRCTCGID], [p5].[YSBTRCID]), [BlockSectionId]
System.Data.SqlClient.SqlException (0x80131904): A column has been specified more than once in the order by list. Columns in the order by list must be unique.
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, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader()
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
ClientConnectionId:f68441e8-baa8-4c16-aa66-0cae875ba173
Error Number:169,State:1,Class:15
[17:00:55 ERR] An exception occurred while iterating over the results of a query for context type 'GCO.Data.GcoContext'.
System.Data.SqlClient.SqlException (0x80131904): A column has been specified more than once in the order by list. Columns in the order by list must be unique.
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, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader()
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
at Microsoft.EntityFrameworkCore.Query.QueryMethodProvider._InjectParameters[TElement](QueryContext queryContext, IEnumerable`1 source, String[] parameterNames, Object[] parameterValues)+MoveNext()
at Microsoft.EntityFrameworkCore.Query.QueryMethodProvider._GroupBy[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector)+MoveNext()
at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable`1 source, Int32& length)
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.OrderedEnumerable`1.GetEnumerator()+MoveNext()
at System.Linq.Enumerable.SelectIPartitionIterator`2.MoveNext()
at System.Collections.Generic.List`1.AddEnumerable(IEnumerable`1 enumerable)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at lambda_method(Closure , TransparentIdentifier`2 )
at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
ClientConnectionId:f68441e8-baa8-4c16-aa66-0cae875ba173
Error Number:169,State:1,Class:15
System.Data.SqlClient.SqlException (0x80131904): A column has been specified more than once in the order by list. Columns in the order by list must be unique.
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, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader()
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
at Microsoft.EntityFrameworkCore.Query.QueryMethodProvider._InjectParameters[TElement](QueryContext queryContext, IEnumerable`1 source, String[] parameterNames, Object[] parameterValues)+MoveNext()
at Microsoft.EntityFrameworkCore.Query.QueryMethodProvider._GroupBy[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector)+MoveNext()
at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable`1 source, Int32& length)
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.OrderedEnumerable`1.GetEnumerator()+MoveNext()
at System.Linq.Enumerable.SelectIPartitionIterator`2.MoveNext()
at System.Collections.Generic.List`1.AddEnumerable(IEnumerable`1 enumerable)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at lambda_method(Closure , TransparentIdentifier`2 )
at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
ClientConnectionId:f68441e8-baa8-4c16-aa66-0cae875ba173
Error Number:169,State:1,Class:15
Exception thrown: 'System.Data.SqlClient.SqlException' in Microsoft.EntityFrameworkCore.dll
[17:00:55 INF] Executed action GCO.App.Controllers.MareysChart.MareysChartController.GetInitialData (GCO.App) in 331.5571ms
[17:00:55 INF] Executed endpoint 'GCO.App.Controllers.MareysChart.MareysChartController.GetInitialData (GCO.App)'
Exception thrown: 'System.Data.SqlClient.SqlException' in System.Private.CoreLib.dll
[17:00:55 ERR] An unhandled exception has occurred while executing the request.
System.Data.SqlClient.SqlException (0x80131904): A column has been specified more than once in the order by list. Columns in the order by list must be unique.
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, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader()
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
at Microsoft.EntityFrameworkCore.Query.QueryMethodProvider._InjectParameters[TElement](QueryContext queryContext, IEnumerable`1 source, String[] parameterNames, Object[] parameterValues)+MoveNext()
at Microsoft.EntityFrameworkCore.Query.QueryMethodProvider._GroupBy[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector)+MoveNext()
at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable`1 source, Int32& length)
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.OrderedEnumerable`1.GetEnumerator()+MoveNext()
at System.Linq.Enumerable.SelectIPartitionIterator`2.MoveNext()
at System.Collections.Generic.List`1.AddEnumerable(IEnumerable`1 enumerable)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at lambda_method(Closure , TransparentIdentifier`2 )
at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
at System.Collections.Generic.List`1.AddEnumerable(IEnumerable`1 enumerable)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at GCO.App.MareysChart.Services.TrainService.GetTrains(DateTime start, DateTime end, List`1 trackCircuitIds) in C:\Projects\VSTS\GCO_server-dotnet\GCO\GCO\MareysChart\Services\TrainService.cs:line 66
at GCO.App.Controllers.MareysChart.MareysChartController.GetInitialData(Int64 tabId, String dateUtcString) in C:\Projects\VSTS\GCO_server-dotnet\GCO\GCO\Controllers\MareysChart\MareysChartController.cs:line 269
at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at System.Threading.Tasks.ValueTask`1.get_Result()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
at GCO.App.Middlewares.UserInfoMiddleware.InvokeAsync(HttpContext httpContext, GcoContext dbContext, ILuwakUserInfoAccessor userInfoAccessor) in C:\Projects\VSTS\GCO_server-dotnet\GCO\GCO\Middlewares\UserInfoMiddleware.cs:line 94
at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.InvokeCore(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
ClientConnectionId:f68441e8-baa8-4c16-aa66-0cae875ba173
Error Number:169,State:1,Class:15
[17:00:55 INF] Request finished in 556.6788ms 500 text/html; charset=utf-8
If I remove the GroupBy altogether it works (but I have duplicated data).
Am I doing something wrong? Why is it generating duplicate order by's? Why is it generating Order By at all? Does Group By translates to an order by?
More strange, this happened to a collegue. In my database this was working just fine. I asked her to make a dump for me to debug. In both cases we have no data on the TrainMovementPlanned table...
I am constantly getting EntityCommandExecutionException while executing simple query.
The query occurs in context of transaction and this is usually happens when there are many threads locking some of the database tables.
I use serialized lock and have a retry pattern, although retries work when deadlock occur i cant figure out how to handle this error or why it could be thrown.
Time: 9/26/2016 9:01:53 PM
Message: System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Transaction (Process ID 59) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
at System.Data.SqlClient.SqlConnection.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.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, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
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.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
--- End of inner exception stack trace ---
at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
--- End of inner exception stack trace ---
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at GizmoDALV2.DefaultDbContext.SaveChanges()
at ServerService.Service.SessionSetState(Int32 sessionId, SessionState state, DefaultDbContext cx)
at ServerService.Service.<>c__DisplayClass780_0.<OnProcessUserHostConnect>b__0()
at GizmoDALV2.DefaultDbContext.RetryBeforeThrow(Action action, Int32 retries, Int32 minWaitTime, Int32 maxWaitTime)
at GizmoDALV2.DefaultDbContext.RetryBeforeThrow(Action action, Int32 retries, Int32 minWaitTime, Int32 maxWaitTime)
at ServerService.Service.OnProcessUserHostConnect(HostComputer hostComputer, ClientDispatcher dispatcher)
at ServerService.Service.OnClientConnection(IConnection sender, Socket socket)
Member name: OnClientConnection
Source file path: D:\My Documents\Visual Studio 2015\Projects\Gizmo\GizmoService\GizmoService\Service\Service_Network.cs
Source line number: 702
Any possible causes for this ?
So I am literally a new DBA and my machine has not been properly setup yet so every time someone sends in a request for an unknown error I am in charge of searching google for answers (hopefully changes by next week! sigh). So after searching on the internet for the past 2 hours I have yet to know what is causing the error that one of the guy sent to me. We are running sql server 2012 and we’re on patch level SP2/CU2.
The error message is
System.Data.SqlClient.SqlException: Cannot insert data into CertainLog table.
dbo.usp_insertcertainlog - EXECUTEPROCEDURE raisedSystem.Data.SqlClient.SqlException
Instancesomething306(ROOT:certainwebsite.somewebsite.com)
The error occurs repeatedly in the certainwebsite.somewebsite.com webservice.
Here is a sample stack trace
> at System.Data.SqlClient.SqlConnection.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.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.InternalExecuteNonQuery(TaskCompletionSource`1
> completion, String methodName, Boolean sendToPipe, Int32 timeout,
> Boolean asyncWrite) at
> System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at
> System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at
> Microsoft.Practices.EnterpriseLibrary.Data.Database.DoExecuteNonQuery(DbCommand
> command) at
> Microsoft.Practices.EnterpriseLibrary.Data.Database.ExecuteNonQuery(DbCommand
> command) at
> Microsoft.Practices.EnterpriseLibrary.Data.Database.ExecuteNonQuery(DbCommand
> command)
From the error it appears that account does not have access to insert data. You will need to modify the permissions.
`if cmd.ExecuteScalar = 1 then
`Server Error in '/BookShop' Application.
Line 1: Incorrect syntax near '='.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near '='.
Source Error:
Line 64: con.Open()
Line 65: Dim cmd As New SqlCommand(sql, con)
Line 66: If cmd.ExecuteScalar() Then
Line 67: Session("EntryNumber") = Val(TextBox2.Text)
Line 68: Response.Redirect("order.aspx")
Source File: D:\Review Material\DIPLOMA\DOTNET FULL PROJECTS\DPEE02\DPEE02\CODING\BookShop\BookDetails.aspx.vb Line: 66
Stack Trace:
[SqlException (0x80131904): Line 1: Incorrect syntax near '='.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +98
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +82
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +346
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +3430
System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +52
System.Data.SqlClient.SqlDataReader.get_MetaData() +130
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +371
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +1272
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +334
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +45
System.Data.SqlClient.SqlCommand.ExecuteScalar() +161
BookShop.BookDetails.Button2_Click(Object sender, EventArgs e) in D:\Review Material\DIPLOMA\DOTNET FULL PROJECTS\DPEE02\DPEE02\CODING\BookShop\BookDetails.aspx.vb:66
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +96
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +116
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +31
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +32
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +72
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3825
Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433
This is probably an error in the SQL that is being executed - the contents of the SQL variable. Can you post this please?
We have a very strange error that sometimes we get this error when we want to save something from our WCF service. The object that we are saving contains NO invalid datetimes, we all check them before we save. When we see this error the database hangs sometimes and the WCF is in a faulty state. When I restart the DB and the IIS web app where the WCF is hosted and try to save again. It works..
We are clueless so if any one has some advice, please share
Following is the error:
2010-03-05 10:21:34,311 [5] ERROR ProjectX.Business.TTExceptionLogger - Exception somewhere in ReceiveResultsForMobile(): {0}
Castle.Services.Transaction.CommitResourceException: Could not commit transaction, one (or more) of the resources failed ---> System.Data.SqlTypes.SqlTypeException: SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
at System.Data.SqlTypes.SqlDateTime.FromTimeSpan(TimeSpan value)
at System.Data.SqlTypes.SqlDateTime.FromDateTime(DateTime value)
at System.Data.SqlClient.MetaType.FromDateTime(DateTime dateTime, Byte cb)
at System.Data.SqlClient.TdsParser.WriteValue(Object value, MetaType type, Byte scale, Int32 actualLength, Int32 encodingByteSize, Int32 offset, TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParser.TdsExecuteRPC(_SqlRPC[] rpcArray, Int32 timeout, Boolean inSchema, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, Boolean isCommandProc)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at NHibernate.AdoNet.AbstractBatcher.ExecuteNonQuery(IDbCommand cmd)
at NHibernate.AdoNet.NonBatchingBatcher.AddToBatch(IExpectation expectation)
at NHibernate.Persister.Entity.AbstractEntityPersister.Update(Object id, Object[] fields, Object[] oldFields, Object rowId, Boolean[] includeProperty, Int32 j, Object oldVersion, Object obj, SqlCommandInfo sql, ISessionImplementor session)
at NHibernate.Persister.Entity.AbstractEntityPersister.UpdateOrInsert(Object id, Object[] fields, Object[] oldFields, Object rowId, Boolean[] includeProperty, Int32 j, Object oldVersion, Object obj, SqlCommandInfo sql, ISessionImplementor session)
at NHibernate.Persister.Entity.AbstractEntityPersister.Update(Object id, Object[] fields, Int32[] dirtyFields, Boolean hasDirtyCollection, Object[] oldFields, Object oldVersion, Object obj, Object rowId, ISessionImplementor session)
at NHibernate.Action.EntityUpdateAction.Execute()
at NHibernate.Engine.ActionQueue.Execute(IExecutable executable)
at NHibernate.Engine.ActionQueue.ExecuteActions(IList list)
at NHibernate.Engine.ActionQueue.ExecuteActions()
at NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session)
at NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent event)
at NHibernate.Impl.SessionImpl.Flush()
at NHibernate.Transaction.AdoTransaction.Commit()
at Rhino.Commons.NHibernateTransactionAdapter.Commit()
at Rhino.Commons.Facilities.RhinoTransactionResourceAdapter.Commit()
at Castle.Services.Transaction.AbstractTransaction.Commit()
--- End of inner exception stack trace ---
at Castle.Services.Transaction.AbstractTransaction.Commit()
at Castle.Services.Transaction.StandardTransaction.Commit()
at Castle.Facilities.AutomaticTransactionManagement.TransactionInterceptor.Intercept(IInvocation invocation)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at IReceiveServiceProxy61c28a82c9a24e96957e32292b924889.Save(Receive instance)
at WcfInterfaceService.MobileServices.SaveReceiveLines(IEnumerable1 receiveLines, String warehouseCode, String username, String deviceNumber, Boolean removeOldReceiveLines) in D:\Project Docs\Clients\ClientX 09.08\Projects\ProjectX\ProjectX.WcfInterfaceService\MobileServices.svc.cs:line 567
at WcfInterfaceService.MobileServices.ProcessReceiveResults(List1 receiveLines, String warehouseCode, String username, String deviceNumber) in D:\Project Docs\Clients\ClientX 09.08\Projects\ProjectX\ProjectX.WcfInterfaceService\MobileServices.svc.cs:line 770
at WcfInterfaceService.MobileServices.ProcessResultsFromMobile(String receiveResult, String warehouseCode, String username, String deviceNumber) in D:\Project Docs\Clients\ClientX 09.08\Projects\ProjectX\ProjectX.WcfInterfaceService\MobileServices.svc.cs:line 668
Are you running SQL Server 2008? I ran into this same error today when using SQL Server 2008. On the database I had set the column to "date" instead of "datetime" because I do not care about the time portion. But there isn't a "date" data type in .NET so you use datetime.
For me I was passing along null datetime values which defaults to something like 1/1/0001 12:00:00 AM. So I was getting the same error you are seeing because it included the time portion.
For me I had to make my datetime value nullable and I also had to use the MsSql2008Dialect in NHibernate which supports the date datatype. More info about NHibernate and SQL Server 2008 here.
I'd check to make sure your database data type is set correctly and that you are using the MsSql2008Dialect if you are using SQL Server 2008.
I have two questions before I can give you an answer:
What kind of database do you use?
What kind of date is causing the exception?
Guess: you are using a database that has a smaller datetime range or accuracy than you use in your code. In that case, the exception is not caused by NHibernate, but by a feature of the database. It's not a bug but a feature.