Create a Shared project with entities and install all required NuGet packages of Entity Framework
Creates Context file by extend class DbContext and user sql connection string as below
Then, In Visual Studio, open NuGet Package Manager Console from Tools -> NuGet Package Manager -> Package Manager Console and enter the following command
Make sure that Default Project points to where your context and entities are, and then execute the command, as shown below.
add-migration 'name of Migration name'
This will create a new folder named Migrations in the project and create the ModelSnapshot files, as shown below.
The Add-Migration command does not create the database. It just creates two snapshot files in the Migrations folder.
1) <timestamp>_<Migration Name>.cs: The main migration file which includes migration operations in the Up() and Down() methods. The Up() method includes the code for creating DB objects and the Down() method includes code for removing DB objects.
2) <contextclassname>ModelSnapshot.cs: A snapshot of your current model. This is used to determine what changed when creating the next migration.
Now, to create a database, use the update-database command in the Package Manager Console, as shown below.
Update-Database -verbose
Apply Migrations for Modified Entities/Configurations
Suppose we add a new entity or modify an existing entity or change any configuration, then we again need to execute the add-migration and update-database commands to apply changes to the database schema.
Now, to sync our "Db" database with these changes, execute the following commands:
add-migration "ModifiedStudentEntity"
This will generate another snapshot in the Migrations folder.
Now, to update the database schema, execute the update-database command in PMC/PowerShell. This will add the columns in the Student table, as shown below.
In this way, you can keep adding, modifying or removing entities from EF Core model and sync the database using migrations.
Reverting Migration
For some reason, if you want to revert the database to any of the previous states then you can do it by using the update-database <migration-name> command.
For example, we modified the Student entity and added some more properties. But now we want to revert it back to the state of the "InitialSchoolDB" migration. We can do it by using the following command:
Update-database "InitialSchoolDB"
The above command will revert the database based on a migration named InitialSchoolDB and remove all the changes applied by the second migration ModifiedStudentEntity. This will also remove ModifiedStudentEntity entry from the __EFMigrationsHistory table in the database.
