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

Kgn-web picture Kgn-web · Nov 21, 2018 · Viewed 37.6k times · Source

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.

Answer

Hani picture Hani · Jun 18, 2019

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).