Controlling Database
Creation and Schema
Changes with Migrations
Julie Lerman
EF Core Expert and Software Coach
@julielerman | thedatafarm.com
Module Overview of EF Core Migrations API
Overview Setting up your project and Visual Studio
for migrations
Create and inspect a migration file
Using EF Core Migrations to create a
database or database scripts
Reverse engineer an existing database into
classes and DbContext
Understanding EF Core Migrations
EF Core Needs to Comprehend the DB Schema
Build SQL from Materialize query Build SQL to save
your LINQ queries results into objects data into database
Mapping Your Data Model to the Database
+
DbContext Conventional and Database schema
custom mappings
Mapping knowledge can
also be used to evolve the
database schema.
EF Core Basic Migrations Workflow
Define/Change Create a Apply Migration
Model Migration File to DB or Script
Source-control friendly
Getting and Understanding the
Design-Time Migrations Tools
Creating and executing
migrations happens at
design time
Migration Commands Lead to Migrations APIs
PowerShell dotnet CLI
migrations commands migrations commands
add-migration dotnet ef migrations add
Command logic
Migrations APIs
Migration Commands Lead to Migrations APIs
PowerShell dotnet CLI
migrations commands migrations commands
Microsoft.EntityFrameworkCore.Tools dotnet tool install dotnet-ef
Command logic
Tools depends on Design Microsoft.EntityFrameworkCore.Design
Design depends on Relational Migrations APIs
Microsoft.EntityFrameworkCore.Relational
Bottom Line
• Add Tools package to project • Install the tools on your system
• Design comes for “free” • Design package in your project
Visual Studio (Windows) Command Line
Check IDE changes
The executable project
Which Project
Gets the Tools?
Getting the Package Manager Console
Ready to Use Migrations
Using Migrations in Visual Studio
When EF Core Is in a Class Library Project
Install Microsoft.EntityFrameworkCore.Tools package into
executable project (e.g., console)
Ensure the executable project is the startup project
Set Package Manager Console (PMC) “default project” to class
library with EF Core (e.g., data)
Run EF Core Migration PowerShell commands in PMC
Using Migrations in dotnet CLI
Add EF Use
Add EF Core tools Core Design** “dotnet ef”
to system* package to commands at
executable project command line
*Command to install: dotnet tool install –global dotnet-ef
**Microsoft.EntityFrameworkCore.Design
Adding Your First Migration
Add-Migration Tasks for Initial Schema
Create a migration file
Read DbContext and
describing how to construct
determine data model
the database schema
Inspecting Your First Migration
Add-Migration Tasks for Model Changes
Read DbContext to
determine data model
Create updated Compare data model to
snapshot file snapshot
Generate migration file
to apply the deltas
For EF 6 users:
EF Core migrations is orders
of magnitude easier to use
in source control
Some EF Core Mapping Conventions (Defaults)
DbSet name is the table name
Class property name is the column name
Strings are determined by provider
e.g., SQL Server: nvarchar(max)
Decimals are determined by provider
e.g., SQL Server: decimal(18,2)
“Id” or “[type]Id” are primary keys
Maps Strings to Non-Nullable Columns by Default
SQL Server SQLite
Using Migrations to Script or Directly
Create the Database
Applying Migrations
Migration File
Applying Migrations
Migration File
Update-Database
Script-Migration
Applying Migrations Directly to the Database
Migration File
Update-Database
• Reads migration file
• Generates SQL in memory
• Creates the database if needed
• Runs SQL on the database
CLI: dotnet ef database update
Applying Migrations into a SQL Script
Migration File
• Reads migration file
• Generates SQL
• Default: Displays SQL in editor
• Use parameters to target file name etc.
Script-Migration
CLI: dotnet ef migrations script
Migrations Recommendation
Development database Production database
update-database script-migration
We will create a fresh
database in this module.
What If Database Does Not Exist?
update-database script-migration
API’s internal code will create the database You must create the database before
before executing migration code running the script
Seeding a Database via Migrations
modelBuilder.Entity<EntityType>().HasData(parameters)
modelBuilder.Entity<Author>().HasData(new Author {Id=1, FirstName=“Julie”, .. };
Specify Seed Data with ModelBuilder HasData Method
Provide all non-nullable parameters including keys and foreign keys
HasData will get translated into migrations
Inserts will get interpreted into SQL
Data will get inserted when migrations are executed
Add-Migration Tasks for Model Changes
Read DbContext to
determine data model
...and any seeding code
Create updated Compare data model to
snapshot file snapshot
...and seeding instructions
Generate migration file
to apply the deltas
Seeding with HasData will
not cover all use cases for
seeding
Use Cases for Seeding with HasData
Mostly static seed data Sole means of seeding
No dependency on anything Provide test data with a
else in the database consistent starting point
HasData will also be
recognized and applied by
EnsureCreated().
Scripting Multiple Migrations
Scripting migrations
requires more control, so it
works differently than
update-database.
Some Scripting Options
script-migration script-migration
script-migration
-idempotent FROM TO
Default: Scripts every Scripts all migrations FROM: Specifies last
migration but checks for each migration run, so start
object first e.g., table at the next one
already exists TO: final one to apply
Reverse Engineering an Existing
Database
Scaffolding Builds DbContext and Entity Classes
Creates Entities from Discovered Database Objects
Tables Views
Reverse Engineer with the Scaffold Command
EF Core CLI
PowerShell
dotnet ef dbcontext
Scaffold-DbContext
scaffold
Scaffolding Limitations
Updating model when Transition to migrations is not
database changes is not pretty. Look for helpful link in
currently supported resources
The Many Parameters of scaffold-dbcontext
EF Core Power Tools for Visual Reverse Engineering
VS extension: ErikEJ.EFCorePowerTools
Free
Open-source
(github.com/ErikEJ/EFCorePowerTools)
Built and maintained by Erik Ejlskov Jensen
Many more features besides reverse engineer
How EF Core Determines Mappings to DB
Override with Override with
Conventions Fluent Mappings Data Annotations
Default assumptions Apply in DbContext
Apply in entity
using Fluent API
property name=column name modelBuilder.Entity<Book>() [Column(“MainTitle")]
.Property(b => b.Title) public string Title{get;set;}
.HasColumnName(“MainTitle");
Scaffolding
Scaffolded classes are a “stake in the ground” to get you started
You can refactor to incorporate your business logic
There is a lot of flexibility and even other tools
Workflow of how EF Core determines
database schema
Review Where Migrations API and tools fit in
PowerShell or CLI commands for
creating and executing migrations
Created and explored a migrations file
Used migrations commands to generate
script or create a new database directly
Reverse engineer existing database into
classes and DbContext
Up Next:
Defining One-to-Many Relationships
Resources
Entity Framework Core on GitHub: github.com/dotnet/efcore
EF Core Tools Documentation: docs.microsoft.com/ef/core/cli/
EF Core Power Tools Extension (model visualizer, scaffold and more):
https://github.com/ErikEJ/EFCorePowerTools
Resources Cont.
EF Core migrations with existing database schema: cmatskas.com/ef-core-
migrations-with-existing-database-schema-and-data
Scott Hanselman “Magic Unicorn” blog post:
hanselman.com/blog/entity-framework-magic-unicorn-and-much-more-is-now-
open-source-with-take-backs