Keeping Domain Model and Database Schema Sync in EF Core

As we start developing a project with .NET Core API and EF Core domain classes what we have used will change so the corresponding changes needs to done on database schema otherwise database schema will go out of sync and our application will not work. However, one thing to remember here manual changes in the database is not allowed we achieve that through migrations we use a migration to keep our domain models sync up with database schema.

Steps to follow,

When you are changing something in the model we need to execute Add-Migration Command let see an example of it,

I have a table called TestItem having columns id, testcol and testcol2 now I decided to add one more column called testcol3 now to reflect this column in the database we need to execute Add-Migration as shown below,

PM> Add-Migration Addnewcol

After this migration file will be generated with name what you specified by you for migration in our case Addnewcol.cs includes changes content,

using Microsoft.EntityFrameworkCore.Migrations;

Now if you want to undo this migration you can execute a command called Remote-Migration to undo this command but once you execute Update-Database you are not allowed to execute Remote-Migration as shown below,

PM> Update-Database

So if you want to revert back already applied changes of the database just check your table,

[dbo].[__EFMigrationsHistory] and check the entry which is before what you have changed and execute the command of Update-Database with migration name as shown below,

Migration Table
PM> Update-Database testitemadd

With this migration what happens, it will compare with the AppDbContext snapshot model and do the changes is snapshot accordingly.

Thank You, See you in the next article !!

You can reach out to me here,

LinkedIn: https://www.linkedin.com/in/vaibhav-bhapkar

Email: vaibhavbhapkar.medium@gmail.com

If you want some technical topics to be discussed with group of participants please raise a request on following link: http://myblogsenquiry.somee.com/

Technical Speaker | Computer Engineer | Full Stack Web Developer | ML Enthusiast | * Knowledge Shared = Knowledge² *