entity-frameworkasp.net-coreef-database-first

EF How can I update my Database with Migrations


So, i started with this command:

Scaffold-DbContext "ConnectionString" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context MyContext -DataAnnotations -Force

*I think ConnectionString is self-explanatory.

After that, i see in my project the represented classes from the database.

Now My Question: How can i update the database correctly?

I started with adding an migration.

dotnet ef migrations add InitialCreate

Now I try to use this migration on my database with the following command.

dotnet ef database update

Finally i get an Error:

Error Number:2714,State:6,Class:16 There is already an object named '...' in the database.

When i try to add an new migration, I use the migration command and the name of the migration. But the InitialCreate migration start first.

Can anyone help me with my problem? Or what is my mistake. What am I doing wrong?


Solution

  • If you start from code-first. Then add-migration and update-database. Check the Database, you will find one more table named dbo._EFMigrationHistory.

    enter image description here

    This table has the record of "migration file name" and "efcore version"

    enter image description here
    enter image description here enter image description here

    So you could create this table on your own. and fill any "migration file name" and "efcore version". It will skip listed files and use the files which not in this table yet. After update, it will record the used migration file. (You could copy the "dbo._EFMigrationHistory" from another code-first project)