Migrate your DB from Database-First to Code-First — EF Core 2.0

Uthpala Pathirana
2 min readNov 22, 2019
(Entityframeworkschool.com, 2019)

Having an application quite stable, we wanted to automate the DB modification using code-first approach. It’s recommended to practise this at the initial stage of the project especially for .NET Core projects.

My entity objects consisted only of the tables that we usually make changes which means IdentityServer tables were not considered. First of all, we reverse-engineer to add the existing entities and create context classes.

In Package Manager Console, execute the Scaffold-DbContext command to create the full model based on the existing DB. OutputDir— directory to generate the classes. Verbose — shows the steps of the execution.

Scaffold-DbContext [-Connection] [-Provider] [-OutputDir] [-Context] [-Schemas>] [-Tables>] [-DataAnnotations] [-Force] [-Project] [-StartupProject] [<CommonParameters>]PM> Scaffold-DbContext "Server=.\SQLExpress;Database=TestDB;User ID=xxxx;Password=xxxx;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -force -Verbose

If you do not need to seed data during the Initial-Migration, you may skip the next step.

Here, it is mandatory to update EF tools to 2.1 as seeding is a new feature for this version. Following is a sample code to seed data as the properties are created inside OnModelCreating.

modelBuilder.Entity<Blog>(entity => {
entity.Property(e => e.Url).IsRequired();

new Blog {BlogId = 1, Url = "http://sample.com"}

Fore more info about Data-seeding methods, see this

Satisfying part of the implementation is adding a migration which created the table __EFMigrationsHistory in the DB. Run the following command in PMC.

Add-Migration InitialCreate -verbose

This will create a folder named Migrations. Inside that is a file with the migration name which has the code related to the changes and a snapshot file for the context.

A Model Snapshot is the current state of the model stored in a class file named <YourContext>ModelSnapshot.cs The file is added to the Migrations folder when the first migration is created, and updated with each subsequent migration. It enables the migrations framework to calculate the changes required to bring the database up to date with the model. (LearnEntityFrameworkCore)

Apply migrations at runtime with the following code in Startup.cs Configure method.


// Migrate and seed the database during startup. Must be synchronous.
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
serviceScope.ServiceProvider.GetService<ApplicationDbContext> ().Database.Migrate();
catch (Exception ex)

Here, according to my requirement, I check if the DB is in the state of my InitialCreate migration, adding the respective record to __EFMigrationsHistory table. Check this for my Configure method.

Thanks for reading! 😀 If there are better approaches to do this, please comment below for everyone’s knowledge ✌️.



Uthpala Pathirana

Someone who loves heavy rain-fall on a night and mild sun shine the following morning. Passion for travelling, reading & dancing. A typical dev.