Partager via


Code First Migrations: Beta 1 ‘With-Magic’ Walkthrough (Automatic Migrations)

 


The information in this post is out of date.

Visit msdn.com/data/ef for the latest information on current and past releases of EF.

For Automatic Migrations see https://msdn.com/data/jj554735


 

We have released the fourth preview of our migrations story for Code First development; Code First Migrations Beta 1. This release includes a preview of the developer experience for incrementally evolving a database as your Code First model evolves over time.

This post will provide an overview of the functionality that is available inside of Visual Studio for interacting with migrations. We will focus on the workflow that combines automatic and code-based migrations. In this workflow most changes can be automatically calculated and applied. More complex changes are written out to code-based migrations that resides in your project. There is a Code First Migrations: Beta 1 ‘No-Magic’ Walkthrough that shows how this same set of changes can be applied using just code-based migrations without any automatic migrations.

This post assumes you have a basic understanding of the Code First functionality that was included in EF 4.2, if you are not familiar with Code First then please complete the Code First Walkthrough.

 

Building an Initial Model

Before we start using migrations we need a project and a Code First model to work with. For this walkthrough we are going to use the canonical Blog and Post model.

  1. Create a new ‘Beta1AutoDemo’ Console application
    .

  2. Add the EntityFramework NuGet package to the project

    • Tools –> Library Package Manager –> Package Manager Console
    • Run the ‘Install-Package EntityFramework’ command
      .
  3. Add a Model.cs class with the code shown below. This code defines a single Blog class that makes up our domain model and a BlogContext class that is our EF Code First context.

    Note that we are removing the IncludeMetadataConvention to get rid of that EdmMetadata table that Code First adds to our database. The EdmMetadata table is used by Code First to check if the current model is compatible with the database, which is redundant now that we have the ability to migrate our schema. It isn’t mandatory to remove this convention when using migrations, but one less magic table in our database is a good thing right!

     using System.Data.Entity;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Data.Entity.Infrastructure;
    
    namespace Beta1AutoDemo
    {
        public class BlogContext : DbContext
        {
            public DbSet<Blog> Blogs { get; set; }
    
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
            }
        }
    
        public class Blog
        {
            public int BlogId { get; set; }
            public string Name { get; set; }
        }
    }
    

 

Installing Migrations

Now that we have a Code First model let’s get Code First Migrations and configure it to work with our context.

  1. Add the EntityFramework.Migrations NuGet package to the project

    • Run the ‘Install-Package EntityFramework.Migrations’ command in Package Manager Console

      .

  2. The EntityFramework.Migrations package has added a Migrations folder to our project. At the moment this folder just contains a single Configuration class, this class has also been opened for you to edit. This class allows you to configure how migrations behaves for your context.

    We’ll just edit the Configuration class to specify our BlogContext and enable automatic migrations (highlighted below).

    namespace Beta1AutoDemo.Migrations

    {

    using System;

    using System.Data.Entity.Migrations;

    using System.Data.Entity.Migrations.Providers;

    using System.Data.SqlClient;

    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<BlogContext>

    {

    public Configuration()

    {

    AutomaticMigrationsEnabled = true;

               // Seed data:

    // Override the Seed method in this class to add seed data.

    // - The Seed method will be called after migrating to the latest version.

    // - You can use the DbContext.AddOrUpdate() helper extension method to avoid creating

    // duplicate seed data. E.g.

    //

    // myContext.AddOrUpdate(c => c.FullName,

    // new Customer { FullName = "Andrew Peters", CustomerNumber = 123 },

    // new Customer { FullName = "Brice Lambson", CustomerNumber = 456 },

    // new Customer { FullName = "Rowan Miller", CustomerNumber = 789 }

    // );

    //

    }

    }

    }

Our First Automatic Migration

Code First Migrations has two commands that you are going to become familiar with. Add-Migration will scaffold a code-based migration based on changes you have made to your model. Update-Database will apply any pending changes to the database. We are going to avoid using Add-Migration (unless we really need to) and focus on letting Code First Migrations automatically calculate and apply the changes.

  1. Let’s use Update-Database to get Code First Migrations to push this our model to the database.

    • Run the ‘Update-Database’ command in Package Manager Console

      .

  2. Code First Migrations has now created a Beta1Demo.BlogContext database on our local SQL Express instance. We could now write code that uses our BlogContext to perform data access against this database. 

    BlogContextDatabase

 

Our Second Automatic Migration

Let’s make another change and let Code First Migrations automatically push the changes to the database for us.

  1. Let’s introduce a new Post class.

     public class Blog
    {
        public int BlogId { get; set; }
        public string Name { get; set; }     
        public List<Post> Posts { get; set; }
    }
    
    public class Post
    {
        public int PostId { get; set; }
        [MaxLength(200)]
        public string Title { get; set; }
        public string Content { get; set; }
    
        public int BlogId { get; set; }
        public Blog Blog { get; set; }
    }. 
    
  2. Let’s use Update-Database to bring the database up-to-date. This time let’s specify the –Verbose flag so that you can see the SQL that Code First Migrations is running.

    • Run the ‘Update-Database –Verbose’ command in Package Manager Console

      .

Adding a Code Based Migration

Now let’s look at something we might want to use a code-based migration for.

  1. Let’s add a Blog.Rating property.

     public class Blog
    {
        public int BlogId { get; set; }
        public string Name { get; set; }
        public int Rating { get; set; }
        public List<Post> Posts { get; set; }
    }
    
  2. We could just run Update-Database to push these changes to the database. However, were adding a non-nullable Blogs.Rating column, if there is any existing data in the table it will get assigned the CLR default of the data type for new column (Rating is integer, so that would be 0). But we want to specify a default value of 3 so that existing rows in the Blogs table will start with a decent rating. Let’s use the Add-Migration command to write this change out to a code-based migration so that we can edit it.

    The Add-Migration command allows us to give these migrations a name, let’s just call ours ‘MyFirstCodeMigration’.

    • Run the ‘Add-Migration MyFirstCodeMigration’ command in Package Manager Console

      .

  3. In the Migrations folder we now have a new MyFirstCodeMigration migration. The migration is pre-fixed with a timestamp to help with ordering. Let’s edit the generated code to specify a default value of 3 for Blog.Rating.

    The migration also has a code-behind file that captures some metadata. This metadata will allow Code First Migrations to replicate the automatic migrations we performed before this code-based migration. This is important if another developer wants to run our migrations or when it’s time to deploy our application.

     namespace Beta1AutoDemo.Migrations
    {
        using System.Data.Entity.Migrations;
    
        public partial class MyFirstCodeMigration : DbMigration
        {
            public override void Up()
            {
                AddColumn("Blogs", "Rating", c => c.Int(nullable: false, defaultValue: 3));
            }
    
            public override void Down()
            {
                DropColumn("Blogs", "Rating");
            }
        }
    }
    
  4. Our edited migration is looking pretty good, so let’s use Update-Database to bring the database up-to-date.

    • Run the ‘Update-Database’ command in Package Manager Console

 

Back to Automatic Migrations

Fortunately we don’t have to keep using code-based migrations now, we can switch back to automatic migrations for our simpler changes. Code First Migrations will take care of performing the automatic and code-based migrations in the correct order based on the metadata it is storing in the code-behind file for each code-based migration.

  1. Let’s add a Blog.Abstract property to our model.

     public class Post
    {
        public int PostId { get; set; }
        [MaxLength(200)]
        public string Title { get; set; }
        public string Content { get; set; }
        public string Abstract { get; set; }     
    
        public int BlogId { get; set; }
        public Blog Blog { get; set; }
    }
    
  2. Let’s use Update-Database to get Code First Migrations to push this change to the database.

    • Run the ‘Update-Database’ command in Package Manager Console

 

Data Motion / Custom SQL

So far we have just looked at migration operations that can leave all the data in place, now let’s look at something that needs to move some data around. There is no native support for data motion yet, but we can run some arbitrary SQL commands at any point in our script.

We just added the Abstract column but it would be handy to pre-populate it for existing posts using some text from the start of the Content column.

  1. Let’s use the Add-Migration command to let Code First Migrations add an empty migration for us. We’re going to call this migration ‘PopulatePostAbstract’.

    • Run the ‘Add-Migration PopulatePostAbstract’ command in Package Manager Console
  2. Update the migration to run some custom SQL that will populate the Abstract column.

     namespace Beta1AutoDemo.Migrations
    {
        using System.Data.Entity.Migrations;
    
        public partial class PopulatePostAbstract : DbMigration
        {
            public override void Up()
            {
                Sql("UPDATE dbo.Posts SET Abstract = LEFT(Content, 100) WHERE Abstract IS NULL");
            }
    
            public override void Down()
            {
            }
        }
    }
    
  3. Our edited migration looks good, so let’s use Update-Database to bring the database up-to-date. We’ll specify the –Verbose flag so that we can see the SQL being run against the database.

    - Run the ‘Update-Database –Verbose’ command in Package Manager Console.
    

 

Migrate to a Specific Version (Including Downgrade)

So far we have always upgraded to the latest migration, but there may be times when you want upgrade/downgrade to a specific migration.

  1. Let’s say we want to migrate our database to the state it was in after running our ‘MyFirstCodeMigration’ migration. We can use the –TargetMigration switch to downgrade to this migration. This is going to cause some columns that were added as part of an automatic migration to be dropped automatically on the way down. Code First Migrations won’t let this happen without you knowing about it, so we need to specify the –Force switch to acknowledge that we are OK with the potential data loss.

    • Run the ‘Update-Database –TargetMigration:"MyFirstCodeMigration" –Force’ command in Package Manager Console

This command will run the Down script for our ‘PopulatePostAbstract’ migration, then use the automatic pipeline to revert the addition of the Abstract column.

If you want to roll all the way back to an empty database then you can use the Update-Database –TagetMigration:"0" command.

 

Getting a SQL Script

Now that we have performed a few iterations on our local database let’s look at applying those same changes to another database.

If another developer wants these changes on their machine they can just sync once we check our changes into source control. Once they have our new migrations they can just run the Update-Database command to have the changes applied locally. However if we want to push these changes out to a test server, and eventually production, we probably want a SQL script we can hand off to our DBA.

  1. We’re just going to simulate deploying to a second database on the local SQL Express instance. Add an App.config file to your project and include a ‘MySecondDatabase’ connection string.

     <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <connectionStrings>
        <add name="MySecondDatabase"
             providerName="System.Data.SqlClient"
             connectionString="Server=.\SQLEXPRESS;Database=AnotherDatabase;Trusted_Connection=True;"/>
      </connectionStrings>
    </configuration>
    
  2. Now let’s run the Update-Database command but this time we’ll specify the –TargetDatabase flag to use the connection string we just added and the –Script flag so that changes are written to a script rather than just applied.

    • Run the ‘Update-Database –TargetDatabase:"MySecondDatabase" –Script’ command in Package Manager Console

      .

  3. Code First Migrations will run the migration pipeline but instead of actually applying the changes it will write them out to a .sql file for you. Once the script is generated, it is opened for you in Visual Studio, ready for you to view or save.

    Looking at the generated file you will see that Code First Migrations has generated SQL for all the automatic and code-based migrations we performed in the same order that we performed them locally.

 

Summary

In this walkthrough you saw how to use automatic migrations to push model changes to the database. You saw how to scaffold and run code-based migrations when you need more control. You also saw how to upgrade and downgrade your database. Finally we looked at how to get a SQL script that represents the pending changes to a database.

As always, we really want your feedback on what we have so far, so please try it out and let us know what you like and what needs improving.

Rowan Miller

Program Manager

ADO.NET Entity Framework

Comments

  • Anonymous
    December 16, 2011
    Great work, guys, this is looking very promising! But how about automatically updating the database during application startup? Isn't that the whole point of migrations? Why isn't this mentioned anywhere in these walk-throughs?

  • Anonymous
    December 16, 2011
    Already possible : As per David Ebbo's comments in previous alpha 3 blog post. In app_start include something along these lines: var dbMigrator = new DbMigrator(new YourConfiguration()); dbMigrator.Update(); I am already using this successfully, if you want data seeded, you'll have to override the seed method in your DbMigrationsConfiguration

  • Anonymous
    January 03, 2012
    As the two posts are very similar, the difference between this "with magic" and "no magic" is: With magic: Update-Database, (magic), Update-Database, (magic), Update-Database No magic: Update-Database, Add-Migration, Update-Database, Add-Migration, Update-Database :)