This blog will take you to a deep insight about migration process in EF Core.
The Migration is a process which automatically update the database schema based on the changes in the model. This always keep the EF core and database schema in sync. During the process it will build the query which works with our database schema and it also process the data which returns from Database in order to create an object.
Let’s start the migration
Step 1: Install Microsoft.EntityFrameworkCore.Tools package
Switch to ConsoleApp project and download Microsoft.EntityFrameworkCore.Tools package which enables the commonly used commands for migration as listed below
This package should be installed in your executable project, in my case it is a ConsoleApp project
Step 2: Add – Migration
The Add-Migration command is used to generate a migration and snapshot file. Open package manager console and enter the below command
The Initial is a migration name, it can be any name.
Make sure the ConsoleApp is your start up project and the default project in the package manager console should point to EFCoreDemo.Data.
Step 3: Inspecting the Migration
From the above figure you can notice migration folder is created while adding the migration which contains two files
- Snapshot file – This keeps the track of the current state of the model. This file is very important because in next time while adding the migration the EF core will compare with the existing snapshot based on the that it will generate a query to update the schema.
- Migration file – The migration using EFCore Migration API to describe what needs to be happen in database, it contains two method the Up method is used to create a table and the Down method is used to drop the table.
Step 4: Update-Database
Again, open the package manager console and execute the below command
The above command Is used to create a table in the database based on the migration script, if the database is not available in the server it will create a new database and execute the script.
Note: For production environment the Script-Migration command is used to generate the consolidate script based on the model, which should be used to execute in production database.
From this blog, you learned about,
- The workflow of how the EF Core determines the database schema
- Migration API
- PowerShell command for creating and executing the migration
- The migration command to generate the script for production
I hope, you have enjoyed this blog. Your valuable feedback, questions or comments about this blog are always welcome.
Source Code – https://github.com/gowthamece/EFCore