How to fix EF Core database errors after extending IdentityUser in ASP.NET Core 3.1?

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.
sql-server
tsql
asp.net-core
asp.net-core-mvc
entity-framework-core-3.1
asked on Stack Overflow Apr 16, 2020 by NetcoreDeveloper • edited Apr 16, 2020 by Gert Arnold

1 Answer

0

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

answered on Stack Overflow Apr 16, 2020 by MRSessions

User contributions licensed under CC BY-SA 3.0