EF6 EntityCommandExecutionException - sql

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 ?

Related

GroupBy generating wrong OrderBy query

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...

Incorrect syntax near the keyword "INTO"

This is the insert query which is causing error :
public int Insert(User obj){
string query = "INSERT IGNORE INTO tblUser(Name,Photo,Email,Password,Branch,Phone,Address,Authority,Recover_Email,Facebook_ID) values(#name,#photo,#email,#pass,#branch,#phone,#addr,#auth,#re,#fbID) ";
List<SqlParameter> lstp = new List<SqlParameter>();
lstp.Add(new SqlParameter("#name", obj.Name));
lstp.Add(new SqlParameter("#photo", obj.Photo));
lstp.Add(new SqlParameter("#email", obj.Email));
lstp.Add(new SqlParameter("#pass", obj.Password));
lstp.Add(new SqlParameter("#branch", obj.Branch));
lstp.Add(new SqlParameter("#phone", obj.Phone));
lstp.Add(new SqlParameter("#addr", obj.Address));
lstp.Add(new SqlParameter("#auth", obj.Authority));
lstp.Add(new SqlParameter("#re", obj.Recovery_Email));
lstp.Add(new SqlParameter("#fbID", obj.Facebook_ID));
return DBUtility.ModifyData(query, lstp);
}
Exception Details :
System.Data.SqlClient.SqlException: Incorrect syntax near the keyword
'INTO'
Table Definition :
CREATE TABLE [dbo].[tblUser] (
[UserID] INT IDENTITY (1, 1) NOT NULL,
[Name] VARCHAR (100) NULL,
[Photo] VARCHAR (500) NULL,
[Email] VARCHAR (50) NULL,
[Password] VARCHAR (500) NULL,
[Branch] VARCHAR (50) NULL,
[Phone] VARCHAR (50) NULL,
[Address] VARCHAR (500) NULL,
[Recovery_Email] VARCHAR (100) NULL,
[Facebook_ID] VARCHAR (200) NULL,
PRIMARY KEY CLUSTERED ([UserID] ASC)
);
If at all needed, The Stack Trace :
[SqlException (0x80131904): Incorrect syntax near the keyword 'INTO'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +1787814
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5341674
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +546
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1693
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +275
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) +1421
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +177
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) +208
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +163
DataAccess.DBUtility.ModifyData(String query, List`1 lstParams) in c:\Users\ABHISHEK\Documents\Visual Studio 2013\Projects\InventoryManagement\DataAccess\DBUtility.cs:36
BusinessLogic.UserLogic.Insert(User obj) in c:\Users\ABHISHEK\Documents\Visual Studio 2013\Projects\InventoryManagement\BusinessLogic\UserLogic.cs:30
InventoryManagementSys.FacebookSync.AuthorizeUser() in c:\Users\ABHISHEK\Documents\Visual Studio 2013\Projects\InventoryManagement\InventoryManagementSys\FacebookSync.aspx.cs:83
InventoryManagementSys.FacebookSync.Page_Load(Object sender, EventArgs e) in c:\Users\ABHISHEK\Documents\Visual Studio 2013\Projects\InventoryManagement\InventoryManagementSys\FacebookSync.aspx.cs:20
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
System.Web.UI.Control.OnLoad(EventArgs e) +92
System.Web.UI.Control.LoadRecursive() +54
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772
AFAIK, you can not use INSERT IGNORE into SQL SERVER. If you are on SQL SERVER 2008 onwards you can use MERGE to do an INSERT if row does not exist, or an UPDATE. e.g.
MERGE
INTO tmp_final dv
USING tmp_holding_DataValue t
ON t.dateStamp = dv.dateStamp
AND t.itemId = dv.itemId
WHEN NOT MATCHED THEN
INSERT (dateStamp, itemId, value)
VALUES (dateStamp, itemId, value)
Edit: It is clear that you are executing against SQL Server because SQL Server client specific types and methods appear in your stack trace.
Based on comments to the question and answers:
You have got Microsoft's SQL Server RDBMS mixed up with Oracle's MySQL RDBMS.
You need to use T-SQL (Microsoft's SQL dialect) when using SQL Server.
You need to use MySQL's SQL dialect when using MySQL.
While common code to use both can be written, it is significantly more complicated (eg. you need to use the common types (like DbCommand) for most code generating the right concrete types with some form of factory layer).
Either use one RDBMS consistently (the easier option) or build the infrastructure (including restricting yourself to the common parts of the SQL dialects) to work across RDBMSs.

Unable to insert data into a certain table

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.

Why do I get the following error when clicking the ordrer button in my ASP .NET application?

`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?

Failed Castle ActiveRecord TransactionScope causes future queries to be invalid

I am trying to solve an issue when using a Castle ActiveRecord TransactionScope which is rolled back.
After the rollback, I am unable to query the Dog table. The "Dog.FindFirst()" line fails with "Could not perform SlicedFindAll for Dog", because it cannot insert dogMissingName.
using (new SessionScope())
{
try
{
var trans = new TransactionScope(TransactionMode.New, OnDispose.Commit);
try
{
var dog = new Dog
{
Name = "Snowy"
};
dog.Save();
var dogMissingName = new Dog();
dogMissingName.Save();
}
catch (Exception)
{
trans.VoteRollBack();
throw;
}
finally
{
trans.Dispose();
}
}
catch (Exception ex)
{
var dogFromDatabase = Dog.FindFirst();
Console.WriteLine("A dog: " + dogFromDatabase.Name);
}
}
Stacktrace is as follows:
Castle.ActiveRecord.Framework.ActiveRecordException: Could not perform SlicedFindAll for Dog ---> NHibernate.Exceptions.GenericADOException: could not insert: [Mvno.Dal.Dog#219e86fa-1081-490a-92d1-9d480171fcfd][SQL: INSERT INTO Dog (Name, Id) VALUES (?, ?)] ---> System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'Name', table 'Dog'; column does not allow nulls. INSERT fails.
The statement has been terminated.
ved System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
ved System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
ved System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
ved System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
ved System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
ved System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
ved System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
ved System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
ved System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
ved NHibernate.AdoNet.AbstractBatcher.ExecuteNonQuery(IDbCommand cmd)
ved NHibernate.AdoNet.NonBatchingBatcher.AddToBatch(IExpectation expectation)
ved NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Boolean[] notNull, Int32 j, SqlCommandInfo sql, Object obj, ISessionImplementor session)
--- End of inner exception stack trace ---
ved NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Boolean[] notNull, Int32 j, SqlCommandInfo sql, Object obj, ISessionImplementor session)
ved NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Object obj, ISessionImplementor session)
ved NHibernate.Action.EntityInsertAction.Execute()
ved NHibernate.Engine.ActionQueue.Execute(IExecutable executable)
ved NHibernate.Engine.ActionQueue.ExecuteActions(IList list)
ved NHibernate.Engine.ActionQueue.ExecuteActions()
ved NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session)
ved NHibernate.Event.Default.DefaultAutoFlushEventListener.OnAutoFlush(AutoFlushEvent event)
ved NHibernate.Impl.SessionImpl.AutoFlushIfRequired(ISet`1 querySpaces)
ved NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results)
ved NHibernate.Impl.CriteriaImpl.List(IList results)
ved NHibernate.Impl.CriteriaImpl.List()
ved Castle.ActiveRecord.ActiveRecordBase.SlicedFindAll(Type targetType, Int32 firstResult, Int32 maxResults, Order[] orders, ICriterion[] criteria)
--- End of inner exception stack trace ---
ved Castle.ActiveRecord.ActiveRecordBase.SlicedFindAll(Type targetType, Int32 firstResult, Int32 maxResults, Order[] orders, ICriterion[] criteria)
ved Castle.ActiveRecord.ActiveRecordBase.FindFirst(Type targetType, Order[] orders, ICriterion[] criteria)
ved Castle.ActiveRecord.ActiveRecordBase.FindFirst(Type targetType, ICriterion[] criteria)
ved Castle.ActiveRecord.ActiveRecordBase`1.FindFirst(ICriterion[] criteria)
If you look at the stack trace, you'll realize that the invalid dogMissingName record is still hanging around in the session's batched insertion buffer, even after the first attempt to perform the insertion failed. Calling Dog.FindFirst() later in the same session re-triggers an internal Flush() (which attempts once again the failed insert.)
From section 9.6 of the documentation:
From time to time the ISession will
execute the SQL statements needed to
synchronize the ADO.NET connection's
state with the state of objects held
in memory. This process, flush, occurs
by default at the following points
from some invocations of Find() or Enumerable()
from NHibernate.ITransaction.Commit()
from ISession.Flush()
Additionally, from section 9.7.2 of the documentation:
If you rollback the transaction you should immediately close and discard the current session
to ensure that NHibernate's internal state is consistent.
Simply moving using (new SessionScope()) inside the outermost try/catch may be a viable workaround (the initial insertion will fail, raise an exception which will take you out of the SessionScope, likely triggering a second failure on the same insert, failure which you finally catch -- also see "data is not flushed on SessionScope.Flush()" in com.googlegroups.castle-project-users.).
Alternatively, if you don't want to close the session, you should be able to simply change the session default flush behaviour (see the FlushMode class) so that it never flushes unless Flush() is called explicitly (e.g. before committing.) Note that managing flushing in this way will get complex and error-prone very quickly, though.
The key is right on Vlad's answer:
If you rollback the transaction you
should immediately close and discard
the current session to ensure that
NHibernate's internal state is
consistent.
After you understand and apply that, your code should then look like this:
try
{
using (new SessionScope())
using (var trans = new TransactionScope(TransactionMode.New, OnDispose.Commit))
{
try
{
var dog = new Dog { Name = "Snowy" };
dog.Save();
var dogMissingName = new Dog();
dogMissingName.Save();
}
catch (Exception)
{
trans.VoteRollBack();
throw;
}
}
}
catch (Exception ex)
{
using (new SessionScope())
{
var dogFromDatabase = Dog.FindFirst();
Console.WriteLine("A dog: " + dogFromDatabase.Name);
}
}