Migration error: column already exists

Trying to add a migration:

dotnet ef migrations add add_ProductGroup --context migrationsdbcontext
dotnet ef database update --context migrationsdbcontext

And after the Update returns the error: "column "ProductGroupId" of relation "Products" already exists".

The ProductGroup model (I'm doing a migration for it):

public class ProductGroup : IHaveIntegerId
    {
        public int Id { get; set; }
        [Localize] public string Title { get; set; }
        public UserGroup? UserGroup { get; set; }
        public ICollection<Product> Products { get; set; }
        public int? RegionId { get; set; }
        public Region Region { get; set; }
    }

The Products table has a ProductGroupId column.

I previously created a migration and deleted it in VS via TeamExplorer. Maybe the column ProductGroupId wasn't deleted from the table Products. It is not clear how to delete it now

enter a description of the image here

Author: A K, 2020-02-24

1 answers

Unfortunately, you did the wrong thing by deleting the files after you applied the transaction.

The correct thing was to first roll back the migration through Remove-Migration -- it performs all the structure checks, carefully removes the added fields, and deletes the migration files itself.

Remember this command for the future, it will be useful.

How can we get out of the situation and return to the correct, consistent state?:

  1. Manually delete the field via SSMS
  2. In the __EFMigrationsHistory database table, delete the row with your remote migration 20200217112046

This is the most extreme case (it is based on understanding how EF Core works and works), so you also have alternatives.

First, if you have already put the files in version control, you can simply get them back and delete them correctly via Remove-Migration

Secondly, if this is not a production base, but a training base and you are not sorry the data that it contains -- you can simply delete the database and create it again by giving the Update-Database command.

Important! In any case, I would recommend that you first do backup, in case to insure against the fact that something goes wrong the plan.

PS And separately, please note that you have in the *.csproj file after performing Remove-Migration there are still lines for removing migration, they do not interfere, but I like cleanliness, so I delete them and do not commichu.

 0
Author: A K, 2020-02-24 19:42:22