Skip to content

SqlServer Migrations: Rebuild foreign keys #12586

Description

@Anderman

I changed the length of een unique index column with give me the message.

The index 'IX_Invoices_ExternalInvoiceId' is dependent on column 'ExternalInvoiceId'. The index 'IX_Invoices_ExternalInvoiceId' is dependent on column 'ExternalInvoiceId'. ALTER TABLE ALTER COLUMN ExternalInvoiceId failed because one or more objects access this column.

use version

modelBuilder
                .HasAnnotation("ProductVersion", "2.1.1-rtm-30846")`

config

public void Configure(EntityTypeBuilder<Invoice> modelBuilder)
        {
            modelBuilder.Property(e => e.Amount)
                .HasColumnType("decimal(18,2)");
            modelBuilder.Property(e => e.ConceptAmount)
                .HasColumnType("decimal(18,2)");
            modelBuilder.Property(e => e.DebitorId)
                .HasColumnType("varchar(50)");
            modelBuilder.Property(e => e.TheirReference)
                .HasColumnType("varchar(24)");
            modelBuilder.Property(e => e.ExternalInvoiceId)
                .HasColumnType("varchar(12)");
            modelBuilder.Property(e => e.Username)
                .HasMaxLength(250);
            modelBuilder.Property(e => e.InvoiceType)
                .HasColumnType("varchar(50)");
            modelBuilder
                .HasIndex(x => new {x.ExternalInvoiceId})
                .IsUnique();
        }

old config

public void Configure(EntityTypeBuilder<Invoice> modelBuilder)
        {
            modelBuilder.Property(e => e.Amount)
                .HasColumnType("decimal(18,2)");
            modelBuilder.Property(e => e.ConceptAmount)
                .HasColumnType("decimal(18,2)");
            modelBuilder
                .HasIndex(x => new {x.ExternalInvoiceId})
                .IsUnique();
        }

generated migration

protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.RenameColumn(
                name: "TheirAmount",
                table: "Invoices",
                newName: "ConceptAmount");

            migrationBuilder.AlterColumn<string>(
                name: "Username",
                table: "Invoices",
                maxLength: 250,
                nullable: true,
                oldClrType: typeof(string),
                oldNullable: true);

            migrationBuilder.AlterColumn<string>(
                name: "TheirReference",
                table: "Invoices",
                type: "varchar(24)",
                nullable: true,
                oldClrType: typeof(string),
                oldNullable: true);

            migrationBuilder.AlterColumn<string>(
                name: "ExternalInvoiceId",
                table: "Invoices",
                type: "varchar(12)",
                nullable: true,
                oldClrType: typeof(string),
                oldNullable: true);

            migrationBuilder.AlterColumn<string>(
                name: "DebitorId",
                table: "Invoices",
                type: "varchar(50)",
                nullable: true,
                oldClrType: typeof(string),
                oldNullable: true);

            migrationBuilder.AddColumn<string>(
                name: "InvoiceType",
                table: "Invoices",
                type: "varchar(50)",
                nullable: true);
        }

Activity

  1. added this to the milestone on Jul 6, 2018
  2. bricelam commented on Jul 6, 2018

    @bricelam
    Contributor

    @Anderman Can you provide a project so I dig into this? The index should be dropped before the ALTER COLUMN statement.

  3. modified the milestones: , on Sep 11, 2018
  4. modified the milestones: , 3.0.0 on Oct 1, 2018
  5. 52 remaining items

  6. removed their assignment
    on Jul 8, 2023
  7. marchy commented on Oct 23, 2023

    @marchy

    What's a viable workaround for when running into this issue?

    Any way to add manual SQL commands or create a multi-step migration to get around the issue?
    (ie: drop foreign relations altogether from all referencing tables, then upgrade the original table, then re-add references back in)

    It would be really helpful if you could include a script with an example script that does this.

    @daunish would you be able to share the script for your solution? (even showing just the lines for one of the dependent tables etc.)

  8. NaserParhizkar commented on Jan 28, 2024

    @NaserParhizkar

    I have similar problem in my project. I only want to change ApplicationUser primary key from string to int and also for IdentityRole as a result I have to change context to ApplicationDbContext(DbContextOptions options) : IdentityDbContext<ApplicationUser,ApplicationRole,int>(options) but when I execute migration I expect migration should have contained a drop index constraint for those which use this primary key. But it only contain a alter code for Id type which leads to a migration Update-Database error.

  9. wqoq commented on Mar 22, 2024

    @wqoq

    Just stumbled across this while looking for a solution/workaround to a similar problem that I'm having. In my case, I'm initiating a multi-phase process to convert a bunch of existing tables whose PKs are strings (aka varchars), but they're really GUIDs and thus could be more efficiently stored as uniqueidentifiers.

    Similar to what people have done above by changing the HasMaxLength value, in my configuration I added a HasConversion<Guid> on the property that acts at the PK on the table.

    The generated migration correctly identifies what I intend to do (change the data type), but when I run or script the migration the resulting SQL only contains an ALTER COLUMN statement which eventually fails the same as other people above:

    ALTER TABLE ALTER COLUMN Id failed because one or more objects access this column
    

    I'm currently using EF Core 7.

    Noteworthy is that this column has no FKs referencing it. However, the PK index on the column itself is what is referencing it. I have other tables I'll need to convert as well that are referenced by other FKs, but I thought I'd start with something simple—a table with no FKs.

    So now I'm contemplating whether I should try to figure out a way to generate the necessary SQL (maybe in a IMigrationsSqlGenerator), or just hand bomb the custom SQL I'll need. Leaning towards the former because I have over 100 PKs I'm going to need to do this for.

  10. InspiringCode commented on Aug 13, 2024

    @InspiringCode

    I am also having the exact same issue as @wqoq here but with EF8. Has anybody found a solution to this? EF should really support this scenario...

  11. wqoq commented on Aug 22, 2024

    @wqoq

    I'll follow-up that I did eventually go with a custom SQL script, but not because of the problem I mentioned above—EF not rebuilding the FKs. Ultimately it was because in my particular scenario, due to some poor choices early on, the GUID values were needlessly being stored in a variable-width data type (varchar) and I'm trying to convert them to a fixed-width data type (uniqueidentifier). When done as an ALTER COLUMN, this is incredibly slow.

    Copying the contents to a new table with the desired data types is much faster. So to get the speed benefits, I had to abandon EF's generated SQL anyway.

  12. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions