It seems like for forever I have been dealing with the problem of deploying software and keeping the database updates synchronized at the same time. I’m sure you’ve been there too. If you are developing software, you likely need database schema changes from time to time (or much more often). If you are running a local copy of the database for development (I like working like that), you can easily make the change on your local SQL Server instance (or some other database product). But then you need all of your teammates to update their database instances with the changes. Of course, they may have changes to the schema as well. All that, plus sooner or later you will need to deploy these changes to the test, staging or production database.

Where I have worked we used a variety of techniques to accomplish this goal but it has never been easy. Finally, Microsoft gives us Entity Framework Migrations! This makes this situation very easy to deal with!

Here are some steps to get started with Migrations. I was surprised with how easy this is to use. To be fair, I haven’t pushed this technology much past the basics but it is working quite nicely on my project so far. Also I’m using EF Code First which is really cool but in this post, I won’t be explaining all of the parts of that. I’ll mention the basic steps but if you want to learn more about the many features of EF Code First, you’ll need to look elsewhere.

Beware, I am running Visual Studio 11 Beta, .Net 4.5 Beta, Entity Framework 5 Beta. You should be able to accomplish this stuff with earlier versions too.

Step By Step Guide to Getting Started with Entity Framework Code First Migrations (in C#)

  1. Create a new application. I’m working with a simple C# Console App.
  2. Install Entity Framework. You can do this via the Nuget Package Manager UI or the Package Manager Console. Again, I am using beta so I’ll need to use the console with this command: PM> install-package EntityFramework –includePreRelease
  3. I did get an error when I did that. I don’t recall getting that error in the past but to resolve the error, I used the Add Reference Dialog and added a reference to System.ComponentModel.DataAnnotations. Then I re-tried the console command and it worked just fine.
  4. After installing EntityFramework, my app.config looks like this:
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <configSections>
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,
    EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> </configSections> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> </entityFramework> </configuration>

    Thanks NuGet!

  5. Next we’ll need to create an entity that needs to be in our database. In my application, I need a simple object to represent movies.
        public class Movie
        {
            public int Id { get; set; }
            public string Title { get; set; }
            public string Year { get; set; }
            public string Studio { get; set; }
        }

    You will note that I did NOT annotate this class with any attributes at all.

  6. Next we’ll need to create our DbContext. It too is pretty simple.
        public class MovieContext : DbContext
        {
            public DbSet<Movie> Movies { get; set; }
        }
  7. Ok for this simple sample, my initial data schema is done. Since this is Code First however, my database doesn’t actually exist yet. Let’s have Entity Framework create it for us. To do so, we need to run our application. Before running it, just add this code to the Main method of your console app. If your application doesn’t “use” the DbContext, it won’t be generated.
        MovieContext context = new MovieContext();
        foreach(var movie in context.Movies)
        {
                    
        }

    Now just run the app. If you’ve got SqlServer Express installed, you will now have a new database in there that looks like this:image

    Yes, the Id was automatically turned into a primary key. Sweet, huh? Code First Rocks!

  8. Now we have a database and a schema but we haven’t used migrations yet! Let’s get started with that. Back in the NuGet Package Manager Console, type this: PM> enable-Migrations 
  9. When you enable migrations, it will create a Migrations folder in your project with two files.
    • 201204190017084_InitialCreate.cs (your name will vary). This file contains the code to create your database schema from scratch. In this case, there is only one table. This will be important because after we do our next migration, we may need to roll back to our initial design.
    • Configuration.cs which is used for… you guessed it, configuration of Migrations. One important setting is AutomaticMigrationsEnabled. With that set to true, EF will always migrate your database when you run your application and it detects that your context is out of sync with your db.
    • Check out these files and you will see how simple this stuff is. Each migration contains an Up() method and a Down() method. This enables you to migrate your database up and down to any version!
          public partial class InitialCreate : DbMigration
          {
              public override void Up()
              {
                  CreateTable(
                      "Movies",
                      c => new
                          {
                              Id = c.Int(nullable: false, identity: true),
                              Title = c.String(),
                              Year = c.String(),
                              Studio = c.String(),
                          })
                      .PrimaryKey(t => t.Id);
                  
              }
              
              public override void Down()
              {
                  DropTable("Movies");
              }
          }
  10. Now we need to make a change: Add something to the Movie class, something like this: public string Genre { get; set; }
  11. Now if we run our application (remember that we do NOT have Automatic Migrations Enabled). We’ll get an error:image

    In this case, that is perfect and just what we expected.

  12. Back to the Package Manager Console: PM> add-migration Genre That command will create a new Migration file for us with just what we need:
        public partial class Genre : DbMigration
        {
            public override void Up()
            {
                AddColumn("Movies", "Genre", c => c.String());
            }
            
            public override void Down()
            {
                DropColumn("Movies", "Genre");
            }
        }
  13. Next, this command in Package Manager Console: PM> update-database You’ll get some messages confirming the action. When I check my database I’ll see that the new column was added just as I needed. I can now run my application successfully again. Too bad my application doesn’t do anything.

Eventually, you will have multiple migrations in your project. If you need to revert back to an old version of code, you can also revert back to an old version of the schema by specifying which a target. In this example, I want to target the migration named “InitialCreate”: update-database –TargetMigration InitialCreate

To create scripts instead of actually updating your database, you can use a command similar to this: update-database -Script -TargetMigration Genre These scripts can be saved and used as part of your deployment process.

Those are the basics of Entity Framework Migrations. I think you will find it is pretty easy to use. For more information, I suggest you follow the ADO.Net Team Blog.

Download my sample solution: MigrationsDemo.zip

One thought on “Entity Framework Code First Migrations: Where have you been all my life?

Leave a reply

required

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>