Skip to content

migrationBuilder.InsertData generates SQL with 'Invalid column name' in idempotent scripts  #17826

Closed as duplicate

Description

@Meberem

I get

Msg 207, Level 16, State 1, Line 2128
Invalid column name 'MyRemovedColumn'

when running an idempotent migrations sql file where I have removed a column after I have inserted data.

In the 1st migration

migrationBuilder.InsertData(
                table: "MyEntity",
                columns: new[] { "EntityId", "MyRemovedColumn" },
                values: new object[] { 1, "Stuff" });

in the 2nd migration

migrationBuilder.RenameColumn(
                name: "MyRemovedColumn",
                table: "MyEntity",
                newName: "Description");

the generated SQL contains

IF NOT EXISTS(SELECT * FROM [__EFMigrationsHistory] WHERE [MigrationId] = N'20190827132005_AddMyEntity')
BEGIN
    IF EXISTS (SELECT * FROM [sys].[identity_columns] WHERE [name] IN (N'EntityId', N'MyRemovedColumn') AND [object_id] = OBJECT_ID(N'[MyEntity]'))
        SET IDENTITY_INSERT [MyEntity] ON;
    INSERT INTO [MyEntity] ([EntityId], [MyRemovedColumn])
    VALUES (1, N'Stuff');
    IF EXISTS (SELECT * FROM [sys].[identity_columns] WHERE [name] IN (N'EntityId', N'MyRemovedColumn') AND [object_id] = OBJECT_ID(N'[MyEntity]'))
        SET IDENTITY_INSERT [MyEntity] OFF;
END;

If this migration has already been run then this part of the script produced the reported error even though it doesn't get run. It appears a way to prevent this error is to wrap the INSERT in an EXEC like so:

IF NOT EXISTS(SELECT * FROM [__EFMigrationsHistory] WHERE [MigrationId] = N'20190827132005_AddMyEntity')
BEGIN
    IF EXISTS (SELECT * FROM [sys].[identity_columns] WHERE [name] IN (N'EntityId', N'MyRemovedColumn') AND [object_id] = OBJECT_ID(N'[MyEntity]'))
        SET IDENTITY_INSERT [MyEntity] ON;
    EXEC('
	INSERT INTO [MyEntity] ([EntityId], [MyRemovedColumn])
    VALUES (1, N''Stuff'');
	');
    IF EXISTS (SELECT * FROM [sys].[identity_columns] WHERE [name] IN (N'EntityId', N'MyRemovedColumn') AND [object_id] = OBJECT_ID(N'[MyEntity]'))
        SET IDENTITY_INSERT [MyEntity] OFF;
END;

Steps to reproduce

  • Create a migration where data is inserted
  • Remove a Column referenced in the inserted data
  • dotnet ef migrations script --idempotent
  • Run the script

Further technical details

EF Core version:
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET Core 2.1

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions