Software University
Download
Report
Transcript Software University
EF Code First (Advanced)
Automatic and Manual Migrations
SoftUni Team
Technical Trainers
Software University
http://softuni.bg
Table of Contents
1. Initialization Strategy
2. Automatic Migrations
3. Manual Migrations
4. Database Seeding
5. Migrations for Production
2
Questions
sli.do
#Entity
3
Code First Model Changes
Design During Initial Development
Changes in Domain Classes
What happens when we change our models?
Entity Framework compares our model with the model from the
__MigrationHistory table in the DB
By default Entity Framework only creates the database
EF doesn't do any schema changes after that
5
Database Initialization Strategy
You can drop and recreate the database if changes are made
May be the most efficient method during early development
Change the DB Initialization strategy from the constructor of
your context:
public MyDBContext() : base("MyConnectionString")
{
Database.SetInitializer(
new DropCreateDatabaseIfModelChanges<MyDBContext>());
}
6
Initialization Strategies
CreateDatabaseIfNotExists
Default migration
DropCreateDatabaseIfModelChanges
We lose all the data when the model changes
DropCreateDatabaseAlways
Great for automated integration testing
MigrateDatabaseToLatestVersion
This option uses our migrations
Custom strategy
Implement IDatabaseInitializer for custom migration strategy
7
Database Seeding
You can place sample data in the DB every time it's recreated
Override the Seed method in an extended strategy class:
public class MyDBInitializer
: DropCreateDatabaseAlways<MyDBContext>
{
Override method
Extend initializer
protected override void Seed(MyDBContext context)
{
// TODO Create and insert sample records
base.Seed(context);
}
}
Resume behavior
of base class
8
Database Migrations
Code First Migrations in Entity Framework
Incremental Changes
We can't always recreate the database when changes arise
Using Code First Migrations we can handle differences between
models and database in a non-destructive way
Preserve existing data
Share changes trough Source Control
Allow rapid deployment in a production environment
10
Code First Migrations in Visual Studio
To enable Migrations, open the Package Manager Console
Tools NuGet Package Manager Package Manager Console
Enter the following command:
Enable-Migrations
This creates an Initial Migration
For additional parameters (e.g. to change Context) see:
get-help Enable-Migrations -detailed
11
Automatic Migrations
To enable Automatic Migrations, enter in the console:
Enable-Migrations –EnableAutomaticMigrations
When the code is changed, a migration will be created
Apply changes to database trough the console:
Print resulting SQL
Update-Database -Verbose
Some changes cannot be done trough automatic migrations
12
Configuring Migrations
Tell Entity Framework to use automatic migrations from the
context constructor:
Database.SetInitializer(
new MigrateDatabaseToLatestVersion<MyDbContext,
Configuration>());
Allow changes that remove existing columns:
This is a generated class,
public Configuration()
found under "Migrations"
{
this.AutomaticMigrationsEnabled = true;
this.AutomaticMigrationDataLossAllowed = true;
}
13
Manual Migrations
Code-based migrations provide full control
To create migration, enter in the console:
Add-Migration [Name]
To apply migration:
Name is optional
Update-Database
To apply specific migration (including going to previous version):
Update-Database –TargetMigration: <Name>
14
Custom Migration Mappings
Two methods are created for each migration:
Up() – update database to current model
Down() – go back to previous version
You can add custom mappings to the Up method
To add an index:
Table name
CreateIndex("Car",
"RegistrationNumber",
true,
Unique?
"IX_Car_BrandId");
Column name
(can be array)
Index name
15
Custom Migration Mappings (2)
When creating non-nullable column, EF will assign the language
specific initial value
To assign custom default value:
Table name
AddColumn("dbo.Blogs",
Data type
"Rating",
c => c.Int(
Column name
nullable: false,
defaultValue: 3));
Default value
16
Custom Migration Mappings (3)
Some times it's best to use raw SQL to update the database
To execute an SQL statement in a migration:
Enable multi-line
strings in C#
Sql(@"UPDATE dbo.Posts
SET Abstract = LEFT(Content, 100)
WHERE Abstract IS NULL");
See the DbMigration documentation for all available commands
17
Seeding the Database
During a migration we can seed the database with some data
using the Seed() method
protected override void Seed(ForumContext context)
{
/* This method will be called after migrating to the latest version.
You can use the DbSet<T>.AddOrUpdate() helper extension method
to avoid creating duplicate seed data. E.g. */
context.Tags.AddOrUpdate(t => t.Text, new Tag { Text = "C#" });
context.SaveChanges();
}
This method will be run after the migration is complete
18
Production Scripts
You can generate an SQL scripts to be run on the production
server by the DBA
Note this has to be run before the migration is applied locally!
Update-Database -script
To create script for specific migration (even if non-pending):
Update-Database –sourcemigration <Name> -script
19
Summary
1. Initializers let you customize the workflow
2. Migrations provide an easy way to make
changes to the code and database
3. You can seed the database with testing data
after each change
20
EF Code First (Advanced)
?
https://softuni.bg/courses/
License
This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons AttributionNonCommercial-ShareAlike 4.0 International" license
Attribution: this work may contain portions from
"Databases" course by Telerik Academy under CC-BY-NC-SA license
Free Trainings @ Software University
Software University Foundation – softuni.org
Software University – High-Quality Education,
Profession and Job for Software Developers
softuni.bg
Software University @ Facebook
facebook.com/SoftwareUniversity
Software University Forums
forum.softuni.bg