Presentation is loading. Please wait.

Presentation is loading. Please wait.

EF Code First (Advanced)

Similar presentations


Presentation on theme: "EF Code First (Advanced)"— Presentation transcript:

1 EF Code First (Advanced)
Automatic and Manual Migrations Code First SoftUni Team Technical Trainers Software University © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

2 Table of Contents Initialization Strategy Automatic Migrations
Manual Migrations Database Seeding Migrations for Production © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

3 sli.do #Entity Questions
© Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

4 Code First Model Changes
Design During Initial Development

5 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

6 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>()); }

7 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

8 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> { protected override void Seed(MyDBContext context) // TODO Create and insert sample records base.Seed(context); } Override method Extend initializer Resume behavior of base class

9 Code First Migrations in Entity Framework
Database Migrations Code First Migrations in Entity Framework

10 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

11 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: This creates an Initial Migration For additional parameters (e.g. to change Context) see: Enable-Migrations get-help Enable-Migrations -detailed

12 Automatic Migrations To enable Automatic Migrations, enter in the console: When the code is changed, a migration will be created Apply changes to database trough the console: Some changes cannot be done trough automatic migrations Enable-Migrations –EnableAutomaticMigrations Print resulting SQL Update-Database -Verbose

13 Configuring Migrations
Tell Entity Framework to use automatic migrations from the context constructor: Allow changes that remove existing columns: Database.SetInitializer( new MigrateDatabaseToLatestVersion<MyDbContext, Configuration>()); This is a generated class, found under "Migrations" public Configuration() { this.AutomaticMigrationsEnabled = true; this.AutomaticMigrationDataLossAllowed = true; }

14 Manual Migrations Code-based migrations provide full control
To create migration, enter in the console: To apply migration: To apply specific migration (including going to previous version): Add-Migration [Name] Name is optional Update-Database Update-Database –TargetMigration: <Name>

15 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 Column name (can be array) CreateIndex("Car", "RegistrationNumber", true, "IX_Car_BrandId"); Unique? Index name

16 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", "Rating", c => c.Int( nullable: false, defaultValue: 3)); Data type Column name Default value

17 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: See the DbMigration documentation for all available commands Enable multi-line strings in C# dbo.Posts SET Abstract = LEFT(Content, 100) WHERE Abstract IS NULL");

18 Seeding the Database During a migration we can seed the database with some data using the Seed() method This method will be run after the migration is complete 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(); }

19 Production Script s 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! To create script for specific migration (even if non-pending): Update-Database -script Update-Database –sourcemigration <Name> -script

20 Summary Initializers let you customize the workflow
Migrations provide an easy way to make changes to the code and database You can seed the database with testing data after each change © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

21 EF Code First (Advanced)
© Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

22 License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license Attribution: this work may contain portions from "Databases" course by Telerik Academy under CC-BY-NC-SA license © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

23 Free Trainings @ Software University
Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software Facebook facebook.com/SoftwareUniversity Software University Forums forum.softuni.bg © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.


Download ppt "EF Code First (Advanced)"

Similar presentations


Ads by Google