Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1.5K
Views
Change the IDENTITY property of a column, the column needs to be dropped and recreated

I am using EF Core 2.1

This was my initial model definition.

public class Customer //Parent
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string Email { get; set; }

    public BankAccount BankAccount { get; set; }

}


public class BankAccount
{
    public int Id { get; set; }

    public string Branch { get; set; }

    public string AcntNumber { get; set; }

    public DateTime CreatedDate { get; set; }

    public int CustomerId { get; set; }

    public Customer Customer { get; set; }

}

But I realized having Id & CustomerId both is overhead as its One-to-One relation, I can update my BankAccount model definition as below.

public class BankAccount
{
    public int Id { get; set; }

    public string Branch { get; set; }

    public string AcntNumber { get; set; }

    public DateTime CreatedDate { get; set; }

    public Customer Customer { get; set; }

}

While in DbContext class defined the principal entity as below.

HasOne(b => b.Customer).WithOne(c => c.BankAccount).HasForeignKey<BankAccount>(f => f.Id);

While running the update-database I am getting the below error.

System.InvalidOperationException: To change the IDENTITY property of a column, the column needs to be dropped and recreated.

However, ideally I should not but just get rid of this error, I deleted the column, constraints and as well table and then the complete database as well. But still the same error.

over 4 years ago · Santiago Trujillo
11 answers
Answer question

0

This error occurs when you try to alter or modify a table that already exists when you want to change schema or the table that already exists, which EF core Doesn't support it yet it needs manual action. here is what you can do about this:

  • Comment related code in migration file to avoid this error.
  • or Remove migration files and create a fresh one.
  • Delete upstream migration and let migration generate new code.
over 4 years ago · Santiago Trujillo Report

0

I had this problem when I tried to change a model from public byte Id {get; set;} to public int Id {get; set;}. To face the issue, I did the following things:

  1. Remove all the migrations until the creation of the target model with Remove-Migration -Project <target_project> in the Package Manager Console
  2. Delete the actual database
  3. If you have some migrations in the middle that you have not created, (for example they came from another branch), copy the migrations files and also the ModelSnapshot file and paste them in your branch (overwrite them carefully!).
  4. create a new migration with add-migration <migration_name> in the Package Manager Console
  5. update the database with update-database in the Package Manager Console

I can solve it in this way because my code was not in a production environment. Maybe you have to face another complex issues if the model is already in there.

over 4 years ago · Santiago Trujillo Report

0

I ran into the same problem, and I solved it by two steps and two migrations:

Step 1

  1. Drop the identity column.
  2. Comment the ID in BankAccount and add a new one (i.e., BankAccountId as
    identity, add migration and update - this drops id).
  3. Add a new column as identity.

Step 2

  1. Drop the newly added column and re-add the previous one. Comment BankAccountId and un-comment ID.
  2. Add migration and update (this drops the BankAccountId and adds Id as identity).
over 4 years ago · Santiago Trujillo Report

0

In my case, table SharedBalances is renamed to Balances and it's identity column SharedBalancesId is renamed BalanceId. SQL commands are executed on SQL Server. You can also try migrationBuilder.Sql(my_sql_command_here)

I created the migration and got the same error.

Rename the column and the table using TSQL command:

EXEC sp_RENAME 'SharedBalances.SharedBalanceId', 'BalanceId', 'COLUMN';

EXEC sp_RENAME 'SharedBalances', 'Balances';

-- Caution: Changing any part of an object name could break scripts and stored procedures.

Comment the RenameTable command in your migration:

/*
migrationBuilder.RenameTable(
    name: "SharedBalances",
    newName: "Balances");
*/

Comment the AddPrimaryKey command in your migration:

/*
migrationBuilder.DropPrimaryKey(
    name: "PK_SharedBalances",
    table: "Balances");
migrationBuilder.AddPrimaryKey(
    name: "PK_Balances",
    table: "Balances",
    column: "BalanceId");
*/

Update occurences of the table name DropForeignKey commands in your migration:

From this....

        migrationBuilder.DropForeignKey(
            name: "FK_SharedBalances_Users_OwnerUserId",
            table: "SharedBalances");

        migrationBuilder.DropPrimaryKey(
            name: "PK_SharedBalances",
            table: "SharedBalances");

To this:

        migrationBuilder.DropForeignKey(
            name: "FK_SharedBalances_Users_OwnerUserId",
            table: "Balances");

        migrationBuilder.DropPrimaryKey(
            name: "PK_SharedBalances",
            table: "Balances");

Now your migration will work. This is how it happened:

over 4 years ago · Santiago Trujillo Report

0

please follow this step:

1-please do all change of identity column in sql server(not in your code first entity framework)

2-comment identity column changes in the migration (.cs file)

3-update-database

enjoy that

over 4 years ago · Santiago Trujillo Report

0

I had to:

  1. Comment the table totally from code
  2. Run a migration that clears it from DB
  3. Uncomment table again with corrected mapping
  4. Run migration again

Done

over 4 years ago · Santiago Trujillo Report

0

In my opinion running the EF Migrations against anything but your development database is asking for trouble as you are naturally limited by the fact that EF migrations will sometimes flatly refuse to work when altering the structure of you objects (changing primary keys and changing foreign keys being the most often encountered).

For many years I have used tools to ensure DB schema is included in version control (complementary to EF migrations). Do your developments to change your dev database (where the data is not important), create multiple migrations but then use the tools to roll these up into a DB deployment script.

Here’s a summary of what I would do in this case: -

  1. Remove (comment out) all references to the old class BankAccount
  2. Create Migration and apply to dev database
  3. Re-Add the BankAccount class with it’s corrected definition
  4. Create Migration and apply to dev database
  5. Use a DB comparison tool (my preference is APEX SQL Diff, but there are other in the marketplace) to create a deployment script that rolls up both migrations.
  6. Test this script on your staging environment (where you should have some data)
  7. If test is good apply to Production

The reality is if you have production data that you want to radically change the structure of with a code first approach it will probably end badly for you unless you understand and address the data migration from one structure to the other.

over 4 years ago · Santiago Trujillo Report

0

I ran into the same problem ( In my case I didn't have any data in the tables ), and I solved it in this way ( It's not the proper way, but it worked for me ):

  1. I've deleted manually migrations from the EFCore project. I removed those lines which have been added from the file _ContextModelSnapshot as well. ( I had one migration which has been applied and one which has been created but it wasn't applied, as I was getting an error - Change the IDENTITY property of a column, the column needs to be dropped and recreated )
  2. I've deleted manually the tables which have been created in the database ( by the first migration)
  3. I've deleted the row in the table _EFMigrationHistory, that one which related to the Migration I wanted to remove.
  4. Re-run VS
  5. Add-Migration NewOneCleanMigration
  6. Update-Database
over 4 years ago · Santiago Trujillo Report

0

For those who are lazy like me: You want to change the datatype of a primary key column "Id" from int to Guid in a table called "Translations" as my case was.

  1. Your generated migration in that case is
migrationBuilder.AlterColumn<Guid>(
     name: "Id",
     table: "Translations",
     type: "uniqueidentifier",
     nullable: false,
     oldClrType: typeof(int),
     oldType: "int")
     OldAnnotation("SqlServer:Identity", "1, 1");

You can delete or comment that out

  1. From the update-database error System.InvalidOperationException: To change the IDENTITY property of a column, the column needs to be dropped and recreated.
  2. We also know that we cannot drop the column without dropping the primary key constraint first. Our new migration becomes
migrationBuilder.DropPrimaryKey(
    name: "PK_Translations",
    table: "Translations");
  migrationBuilder.DropColumn(
    name: "Id",
    table: "Translations");
  migrationBuilder.AddColumn<Guid>(
    name: "Id",
    table: "Translations",
    type: "uniqueidentifier",
    nullable: false);

Remember to do the opposite in the Down override method in case you may want to reverse the migration

over 4 years ago · Santiago Trujillo Report

0

I had a similar problem where I was changing the relational navigation component of a table's configuration from WithMany to WithRequiredDependent. Entity framework wanted to drop the index and recreate the column, even though nothing in the database should have changed.

To fix this, I rescaffolded the latest migration which allowed entity to absorb the change without any new migration being created. You can rescaffold the latest migration by reverting the migration from the target database, and re-running the Add-Migration script for the latest migration with the exact same migration name.

over 4 years ago · Santiago Trujillo Report

0

  1. Table has no important data
  • Rename the table entity.ToTable("BankAccount2")
  • Add Run migration Add-Migration BankAccountTempChanges
  • Update the database Update-Database
  • Rename back the table entity.ToTable("BankAccount")
  • Add Run migration Add-Migration BankAccountOk
  • Update the database again Update-Database
  1. Table has data not to be lost
  • Apply solution from @Hani answer
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!