Migrations: changing key type from string to Guid results in broken migration
See original GitHub issueOriginal code:
public class Blog
{
public string Id { get; set; }
}
public class Program
{
public static void Main()
{
}
}
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Test;ConnectRetryCount=0");
}
Initial migration:
public partial class Initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Blogs",
columns: table => new
{
Id = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Blogs", x => x.Id);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Blogs");
}
}
Change key type to Guid:
public class Blog
{
public Guid Id { get; set; }
}
Key-change migration:
public partial class KeyChange : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<Guid>(
name: "Id",
table: "Blogs",
nullable: false,
oldClrType: typeof(string));
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "Id",
table: "Blogs",
nullable: false,
oldClrType: typeof(Guid));
}
}
Run update-database:
PM> update-database
Applying migration '20180427000202_Initial'.
Applying migration '20180427000334_KeyChange'.
Failed executing DbCommand (32ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
DECLARE @var0 sysname;
SELECT @var0 = [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'[Blogs]') AND [c].[name] = N'Id');
IF @var0 IS NOT NULL EXEC(N'ALTER TABLE [Blogs] DROP CONSTRAINT [' + @var0 + '];');
ALTER TABLE [Blogs] ALTER COLUMN [Id] uniqueidentifier NOT NULL;
System.Data.SqlClient.SqlException (0x80131904): The object 'PK_Blogs' is dependent on column 'Id'.
ALTER TABLE ALTER COLUMN Id failed because one or more objects access this column.
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.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.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:0f72d2ce-88d6-4245-8733-05b6aa1e21b9
Error Number:5074,State:1,Class:16
The object 'PK_Blogs' is dependent on column 'Id'.
ALTER TABLE ALTER COLUMN Id failed because one or more objects access this column.
Issue Analytics
- State:
- Created 5 years ago
- Comments:11 (10 by maintainers)
Top Results From Across the Web
Entity Framework code-first: migration fails with update- ...
You can use the Add-Migration command to write the pending model changes to a code-based migration. I tried AutomaticMigrationsEnabled = true , ...
Read more >Can GUID associated with key be updated with new GUID
There is one migration activity going on in which we are migrating from one provider to a different provider with different GUID.
Read more >Easy Schema Migrations in .NET Core | by Manfred Lange
This mechanism allows Fluent Migrator to keep track of what changes have already been applied to a given database. As a result, merge...
Read more >Migration Guide | Cypress Documentation
This guide details the changes and how to change your code to migrate to Cypress version 12.0. See the full changelog for version...
Read more >Using a Microsoft SQL Server database as a source for ...
AWS DMS supports migrating data from named instances of SQL Server. You can use the following ... To capture changes for tables without...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
This is still a problem.
After thinking/playing some more, I think a workaround could be to remove the initial migration (with
Remove-Migration
), make the key change, then re-create it withAdd-Migration
. However, I then hit this which seems to be an Identity issue.