Home > Mobile >  EF Core: update database error: column "PostalCode" of relation "City" already e
EF Core: update database error: column "PostalCode" of relation "City" already e

Time:02-18

I have a class and in this class there is "PostalCode"

public string CityName { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }

I'm creating a migration

add-migration AddPostalCode

Then I update the database

update-database

Error:

42701: column "PostalCode" of relation "City" already exists

Because PostalCode was added manually to the City table in the database.

Not only PostalCode, there are other manually added fields. How do I update the database by ignoring these fields.

CodePudding user response:

You can either delete the postal code column from the table directly it is assigned too

or

go into your migration that was created from add-migration AddPostalCode and remove the code from the Up section that adds the PostalCode column to the table.

However you should NOT be adding table columns manually to a DB, so if its possible go and delete that column from the DB and let your code first approach be the only way you add columns. Its really bad practice to manually add columns when using EF and code first approach.

CodePudding user response:

If you have an existing schema then you should create a snapshot of it with:

Add-Migration InitialCreate –IgnoreChanges 

Then add your changes to the models i.e. add your PostalCode to the model then add the migration and update:

Add-Migration AddPostalCode
Update-Database
  • Related