I have a mature code-base with a set of SQL migration scripts.
We run the migrations to update or create the database using RoundhousE via a Powershell script.
Until recently these migrations were running successfully, however now I am getting an error on with the actual SQL in the migration scripts.
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near the keyword 'IF'.
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.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at roundhouse.databases.AdoNetDatabase.run_command_with(String sql_to_run, ConnectionType connection_type, IList`1 parameters) in C:\projects\roundhouse\product\roundhouse.core\databases\AdoNetDatabase.cs:line 143
at roundhouse.databases.AdoNetDatabase.run_sql(String sql_to_run, ConnectionType connection_type, IList`1 parameters) in C:\projects\roundhouse\product\roundhouse.core\databases\AdoNetDatabase.cs:line 134
at roundhouse.databases.DefaultDatabase`1.run_sql(String sql_to_run, ConnectionType connection_type) in C:\projects\roundhouse\product\roundhouse.core\databases\DefaultDatabase.cs:line 213
at roundhouse.migrators.DefaultDatabaseMigrator.run_sql(String sql_to_run, String script_name, Boolean run_this_script_once, Boolean run_this_script_every_time, Int64 version_id, EnvironmentSet environment_set, String repository_version, String repository_path, ConnectionType connection_type) in C:\projects\roundhouse\product\roundhouse.core\migrators\DefaultDatabaseMigrator.cs:line 206
at roundhouse.runners.RoundhouseMigrationRunner.traverse_files_and_run_sql(String directory, Int64 version_id, MigrationsFolder migration_folder, EnvironmentSet migrating_environment_set, String repository_version, ConnectionType connection_type) in C:\projects\roundhouse\product\roundhouse.core\runners\RoundhouseMigrationRunner.cs:line 290
at roundhouse.runners.RoundhouseMigrationRunner.log_and_traverse(MigrationsFolder folder, Int64 version_id, String new_version, ConnectionType connection_type) in C:\projects\roundhouse\product\roundhouse.core\runners\RoundhouseMigrationRunner.cs:line 222
at roundhouse.runners.RoundhouseMigrationRunner.run() in C:\projects\roundhouse\product\roundhouse.core\runners\RoundhouseMigrationRunner.cs:line 145
ClientConnectionId:a60834d8-8eb0-4de7-9735-02c53968c4d3
Error Number:156,State:1,Class:15
SqlErrors:
Error Number: 156, Message: Incorrect syntax near the keyword 'IF'.
It isn't an issue with the SQL - the SQL runs fine manually on the database.
The very same migrations run successfully without alteration on my colleagues machine, so it must be something unique to my machine that is causing it.
I have tried:
updating RoundhousE from 1.2.1 to 1.3.1
uninstalling RoundhouseE and re-installing
running the migrations as part of unit tests in Visual Studio test runner
running the migrations as part of unit tests in Jetbrains Rider test runner
running the migrations against an existing database
running the migrations against a bran new database
I get the same SQL error: "Error Number: 156, Message: Incorrect syntax near the keyword 'IF'."
I'm kind of reluctant to post the SQL itself because it isn't an issue with the SQL - these scripts have been ran over and over again locally and in the release pipeline and I don't want to invite recommendations to change the SQL. However, the SQL is:
GO
DROP INDEX IF EXISTS [specialapp].[TypeAnalyis].[IX_TypeAnalysis_UserId]
CREATE NONCLUSTERED INDEX [IX_TypeAnalysis_UserId] ON [specialapp].[TypeAnalyis]
(
[UserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
The RH command being used is:
rh.exe --db SpecialAppDatabase --transaction --silent --files C:\Code\specialapp\src\SpecialApp.Database\sql --instance (localdb)\mssqllocaldb --version unversioned --output C:\Code\specialapp\src\Database\Scripts\log
The actual output is as below:
What could be the setting or difference on my machine that is preventing the migrations running?
This codebase was recently upgraded to .Net 6 so it may be related to that. However as mentioned above, the same RH command works on a colleague's machine.
Related
I am using the Copy Database feature in SSMS. The source instance is v 2012, the target instance is v 2019.
I am able to copy other databases in the source instance to the target instance. This particular database fails.
This message is from the Windows Event Viewer on the target machine. "InnerException-->Invalid column name 'Description'." does not make sense because there is
a column with that name in one of the tables in the source database. I can't tell what table it's complaining about from the message in the Windows Event Log.
There is one table in the source database with a column called Description:
Event Name: OnError
Message: An error occurred while transferring data. See the inner exception for details.
StackTrace: at Microsoft.SqlServer.Management.Smo.Transfer.TransferData()
at Microsoft.SqlServer.Dts.Tasks.TransferObjectsTask.TransferObjectsTask.TransferDatabasesUsingSMOTransfer()
InnerException-->Invalid column name 'Description'.
StackTrace: 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.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Microsoft.SqlServer.Management.Smo.Transfer.ExecuteStatements(SqlConnection destinationConnection, IEnumerable`1 statements, SqlTransaction transaction)
at Microsoft.SqlServer.Management.Smo.Transfer.TransferData()
Operator: NT Service\SQLAgent$MSSQLSERVER2019
Source Name: CDW_IL-SERVER-001_MSSQLSERVER2012_IL-SERVER-002_MSSQLSERVER2019_8
Source ID: {6FCAF562-8C02-4A7F-BDE0-9B985BE99BCB}
Execution ID: {C9D1672E-366F-49C2-B98F-903B080DF36A}
Start Time: 8/14/2020 9:11:21 AM
End Time: 8/14/2020 9:11:21 AM
Data Code: 0
I've built a web app in ASP.NET Core 3.1, using Entity Framework Core 3.1 as well, and am now trying to Publish it to Azure. However, at the point in development when I extended the built-in IdentityUser class with a custom ApplicationUser class, my EF migrations stopped posting to the database. The migrations successfully were created, but the update-database command always failed.
Because I couldn't understand the error messages, I simply manually updated the database tables based on the information contained in each of my subsequent migrations files. This worked fine while still developing, but now that I want to publish the app to Azure, the same errors are preventing the app from being able to host on Azure at all.
Basically, when Azure tries to create the database, the exact same errors that I ran into during development prevent the successful creation of the database. And because I used a manual workaround during development, I have no idea how to solve the errors now when trying to publish the app to Azure.
Below is the error message I get when trying to publish to Azure:
System.AggregateException: One or more errors occurred. ---> System.Exception: Build failed. Check the Output window for more details.
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at Microsoft.WebTools.Publish.PublishService.VsWebProjectPublish.<>c__DisplayClass43_0.b__3()
at System.Threading.Tasks.Task`1.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Publish.Framework.ViewModel.ProfileSelectorViewModel.d__213.MoveNext()
---> (Inner Exception #0) System.Exception: Build failed. Check the Output window for more details.<---
System.Exception: Build failed. Check the Output window for more details.
===================
Severity Code Description Project File Line Suppression State
Error Web deployment task failed. (An error occurred during execution of the database script. The error occurred between the following lines of the script: "568" and "581". The verbose log might have more information about the error. The command started with the following:
"IF NOT EXISTS(SELECT * FROM [__EFMigrationsHisto"
The object 'PK_AspNetUserTokens' is dependent on column 'Name'.
ALTER TABLE ALTER COLUMN Name failed because one or more objects access this column. http://go.microsoft.com/fwlink/?LinkId=178587 Learn more at: http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_SQL_EXECUTION_FAILURE.)
Failed to publish the database. This can happen if the remote database cannot run the script. Try modifying the database scripts, or disabling database publishing in the Package/Publish Web properties page. If the script failed due to database tables already exist, try dropping existing database objects before creating new ones. For more information on doing these options from Visual Studio, see http://go.microsoft.com/fwlink/?LinkId=179181.
Error details:
An error occurred during execution of the database script. The error occurred between the following lines of the script: "568" and "581". The verbose log might have more information about the error. The command started with the following:
"IF NOT EXISTS(SELECT * FROM [__EFMigrationsHisto"
The object 'PK_AspNetUserTokens' is dependent on column 'Name'.
ALTER TABLE ALTER COLUMN Name failed because one or more objects access this column. http://go.microsoft.com/fwlink/?LinkId=178587 Learn more at: http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_SQL_EXECUTION_FAILURE.
The object 'PK_AspNetUserTokens' is dependent on column 'Name'.
ALTER TABLE ALTER COLUMN Name failed because one or more objects access this column.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 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.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Microsoft.Web.Deployment.DBStatementInfo.Execute(DbConnection connection, DbTransaction transaction, DeploymentBaseContext baseContext, Int32 timeout) BethanysPieShop 0
Below is the related error I get any time I run the update-database command in the Package Manager Console during development:
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (1,684ms) [Parameters=[], CommandType='Text', CommandTimeout='120']
DECLARE #var2 sysname;
SELECT #var2 = [d].[name]
FROM [sys].[default_constraints] [d]
INNER JOIN [sys].[columns] [c] ON [d].[parent_column_id] = [c].[column_id] AND [d].[parent_object_id] = [c].[object_id]
WHERE ([d].[parent_object_id] = OBJECT_ID(N'[AspNetUserTokens]') AND [c].[name] = N'Name');
IF #var2 IS NOT NULL EXEC(N'ALTER TABLE [AspNetUserTokens] DROP CONSTRAINT [' + #var2 + '];');
ALTER TABLE [AspNetUserTokens] ALTER COLUMN [Name] nvarchar(128) NOT NULL;
Failed executing DbCommand (1,684ms) [Parameters=[], CommandType='Text', CommandTimeout='120']
DECLARE #var2 sysname;
SELECT #var2 = [d].[name]
FROM [sys].[default_constraints] [d]
INNER JOIN [sys].[columns] [c] ON [d].[parent_column_id] = [c].[column_id] AND [d].[parent_object_id] = [c].[object_id]
WHERE ([d].[parent_object_id] = OBJECT_ID(N'[AspNetUserTokens]') AND [c].[name] = N'Name');
IF #var2 IS NOT NULL EXEC(N'ALTER TABLE [AspNetUserTokens] DROP CONSTRAINT [' + #var2 + '];');
ALTER TABLE [AspNetUserTokens] ALTER COLUMN [Name] nvarchar(128) NOT NULL;
Microsoft.Data.SqlClient.SqlException (0x80131904): The object 'PK_AspNetUserTokens' is dependent on column 'Name'.
ALTER TABLE ALTER COLUMN Name failed because one or more objects access this column.
at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at Microsoft.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean isAsync, Int32 timeout, Boolean asyncWrite)
at Microsoft.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String methodName)
at Microsoft.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
ClientConnectionId:a2c8216d-8ba5-413c-8ab8-1526fdb7a7e7
Error Number:5074,State:1,Class:16
The object 'PK_AspNetUserTokens' is dependent on column 'Name'.
ALTER TABLE ALTER COLUMN Name failed because one or more objects access this column.
I think the best thing you could do in this case, since you don't have any real data to work with yet, is to remove your migrations if you have everything set at where you want it, wipe your database clean, and start your migrations and database from scratch.
I know this isn't the ideal way to handle it, but I think with you starting out with migrations and update-database, and then moving to manually updating the database with the migrations scripts, it's going to be hard and almost impossible to get it back to where you need it.
With a new migration, all of your tables should set correctly without error.
Source: I did the exact same thing as you did, now I'm very careful how I deal with migrations and make sure to apply them properly, and I have no more issues.
If you are using migrations and update-database, stick with that, I wouldn't manually do it with the scripts
I am building out my database using EF Core 2.1 code first migrations. I have altered a table to rename. The migration initially dropped the entire table and then read it with the new name, which had issues with foreign key constraints. I changed the migration to use the RenameTable method instead like
migrationBuilder.RenameTable("TourSpecs", "TourSpecHistory");
When running update-database I get the error
Failed executing DbCommand (27ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
DECLARE #defaultSchema sysname = SCHEMA_NAME();
EXEC(N'ALTER SCHEMA ' + #defaultSchema + N' TRANSFER [TourSpecHistory].[TourSpecs];');
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (27ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
DECLARE #defaultSchema sysname = SCHEMA_NAME();
EXEC(N'ALTER SCHEMA ' + #defaultSchema + N' TRANSFER [TourSpecHistory].[TourSpecs];');
System.Data.SqlClient.SqlException (0x80131904): Cannot find the object 'TourSpecs', because it does not exist or you do not have permission.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 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.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
ClientConnectionId:332393e8-8539-4c80-b24c-6478ec61b55b
Error Number:15151,State:1,Class:16
System.Data.SqlClient.SqlException (0x80131904): Cannot find the object 'TourSpecs', because it does not exist or you do not have permission.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 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.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary2 parameterValues)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary2 parameterValues)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
ClientConnectionId:332393e8-8539-4c80-b24c-6478ec61b55b
Error Number:15151,State:1,Class:16
Cannot find the object 'TourSpecs', because it does not exist or you do not have permission.
Thinking this is just a permissions issue I ran the command
GRANT ALTER ON SCHEMA:: [dbo].[TourSpec] TO ApplicationLogin
But was hit with the error
Cannot find the schema 'dbo.TourSpec', because it does not exist or you do not have permission.
The login I am using to run the grant script has the ALTER ANY SCHEMA permission. What do I need to do to get the correct permissions granted to my ApplicationLogin user?
After #Sean Lange pointed out that I had an incorrect understanding of what was a schema and what an object, I successfully granted the permissions to my user but was still unable to run the migration. Looking through the RenameTable method further, I discovered that it takes in 3 optional arguments at the end and that the migration was incorrectly try to alter a [TourSpecHistory].[TourSpecs] table.
I changed the migration to run migrationBuilder.RenameTable("TourSpecs", "dbo", "TourSpecHistory", "dbo"); and it now works correctly
I've got problem with renaming column and migrating changes to database.
Migration:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "int",
schema: "Gamgoo.More",
table: "Rating",
newName: "GivenRating");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "GivenRating",
schema: "Gamgoo.More",
table: "Rating",
newName: "int");
}
Commands that I'm using are (from Package Manager Console / Powershell):
Add-Migration RatingFix -p Gamgoo.Data.Context -c GamgooContext
Update-Database
And the error message:
Applying migration '20180319172151_RatingFix'.
Microsoft.EntityFrameworkCore.Migrations[200402]
Applying migration '20180319172151_RatingFix'.
fail: Microsoft.EntityFrameworkCore.Database.Command[200102]
Failed executing DbCommand (31ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
EXEC sp_rename N'Gamgoo.More.Rating.int', N'GivenRating', N'COLUMN';
System.Data.SqlClient.SqlException (0x80131904): Either the parameter #objname is ambiguous or the claimed #objtype (COLUMN) is wrong.
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.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
ClientConnectionId:ba25aa03-122d-4c55-9673-4bd3358f2f83
Error Number:15248,State:1,Class:11
Failed executing DbCommand (31ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
EXEC sp_rename N'Gamgoo.More.Rating.int', N'GivenRating', N'COLUMN';
System.Data.SqlClient.SqlException (0x80131904): Either the parameter #objname is ambiguous or the claimed #objtype (COLUMN) is wrong.
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.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_1.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
ClientConnectionId:ba25aa03-122d-4c55-9673-4bd3358f2f83
Error Number:15248,State:1,Class:11
Either the parameter #objname is ambiguous or the claimed #objtype (COLUMN) is wrong.
I've checked ef core github, forum and stackoverflow for similar problems, but those answers did not helped me.
I would like to avoid removing all migrations and updating the database, because I already have quite a lot of data in other tables.
This may have been fixed by PR #11161. You can try the nightly builds.
You can work around the issue by rewriting the sp_rename call:
// UNDONE: SQL generated by EF Core is missing schema identifier quotes
//migrationBuilder.RenameColumn(
// name: "int",
// schema: "Gamgoo.More",
// table: "Rating",
// newName: "GivenRating");
migrationBuilder.Sql(
"EXEC sp_rename N'[Gamgoo.More].[Rating].[int]', N'GivenRating', N'COLUMN';");
I got this same issue while trying to rename a column that I had added to the identity User. After checking the database, I realized that I had created the migration to generate the original column, but never actually updated the database. Earlier in some frustration I had deleted the migration that would have generated the column had I actually updated the database. Fairly easy fix - manually created the original column and then the current migration with the rename worked as expected.
Hopefully my answer may help someone else.
I have an ASP.Net MVC application that uses SQL Server 2005 via NHibernate. I am getting getting the following error message sporadically:
"System.Data.SqlClient.SqlException (0x80131904): Timeout expired.
The timeout period elapsed prior to completion of the operation or the
server is not responding. at
System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection) at
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection) at
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() at
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj) at
System.Data.SqlClient.SqlDataReader.SetMetaData(_SqlMetaDataSet
metaData, Boolean moreInfo) at
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj) at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()
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) at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, DbAsyncResult result) 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.System.Data.IDbCommand.ExecuteReader()
at NHibernate.AdoNet.AbstractBatcher.ExecuteReader(IDbCommand cmd)
at NHibernate.Loader.Loader.GetResultSet(IDbCommand st, Boolean
autoDiscoverTypes, Boolean callable, RowSelection selection,
ISessionImplementor session) at
NHibernate.Loader.Loader.DoQuery(ISessionImplementor session,
QueryParameters queryParameters, Boolean returnProxies) at
NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor
session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoList(ISessionImplementor session,
QueryParameters queryParameters)"
Most of the time the system works fine and is very responsive. I have looked into the locks being held on the system and what I typically find is there is one query being blocked by another query:
"SELECT TOP 10 d.Id, d.Name FROM Documents d INNER JOIN Users u ON..."
is being blocked by:
"SELECT TOP 10 Id, Name FROM Users"
Looking at the locks being held by the blocking statement there are around a dozen exclusive (X) and (IX) page and key locks on various tables unrelated to the Users table (but that are part of the query that is being blocked).
There are no UPDATES, INSERTS or DELETES involved here - so why would one read-only query block the other and why would a simple query on the Users table cause locks on lots of other tables.
A SQL Server gotcha is a non-default "isolation-level" setting on the database. SQL Server has a default isolation-level (locking strategy) of ReadCommitted which means that read locks are released as soon as possible but write locks are not released until a transaction is committed. In Andy's answer, the default isolation-level will cause the select to be blocked. However if the database is set to either RepeatableRead or Serializable, then selects will always block each other for the duration of a transaction. This setting can be controlled in NHibernate with this hibernate.cfg.xml config:
<session-factory>
...
<add key="hibernate.connection.isolation" value="ReadCommitted" />
...
</session-factory>
This would cause the issue:
begin transaction
update Documents
set SomeField = 'SomeValue'
where SomeCondition = 'XXXX'
select top 10 Id, Name from Users
commit
The locks created on the document table during the update won't be released until you commit the transaction. This would mean that a connection could have the select statement as its most recent statement, but still be holding locks from the previous update.
Some ideas:
Make sure you are committing/rolling back your transactions
Try to reduce the length of your transactions (e.g. in the above, would it be safe to commit before running the select?).
Optimizing the join on the update by making sure the foreign key is indexed might also speed up the transaction.
Note that a select itself will only generate shared locks.
Finally beware of the (nolock) lock hint idea. Reading uncommitted data is rarely a good idea.