If you find yourself stuck because you need to use EF 6 features in an ASP.NET Core web app with Identity, don’t worry, it is easy!

Like many of you, I am trying to get all caught up with ASP.NET Core. It has some great features and I’ve been looking forward to using it. I finally have a new project to start so Core was my first choice.To expand on that a bit, I am using ASP.NET Core with the full .NET Framework. At this point, I don’t need to use .NET Core in cross platform scenarios.

It wasn’t long after I got started that I ran into what I thought was a big problem.Spoiler Alert: It wasn’t a big problem at all!

A new project created for ASP.NET Core (configured to use Individual Accounts for security) will be all loaded up with Entity Framework Core as well as Controllers and Views and Code to make all the authentication stuff work. This post isn’t about that. It was all working nicely. That is, until I needed Entity Framework Spatial Types with SQL Server. My website needs to calculate distance between two points, something that is surprisingly easy with the right tools. However, EF Core doesn’t yet support that! I’d needed EF 6 instead. Now, this is where I made my big mistake. I assumed that I couldn’t have EF 6 and EF Core in the same project so I removed all of the EF Core stuff. I began to set up EF 6 instead and ran into issues wiring things up with ASP.NET Core. To set up all of the Dependency Injection stuff and wire up services, you need code like this:

services.AddIdentity<ApplicationUser, IdentityRole>()

But it turns out that AddEntityFrameworkStores doesn’t exist in EF 6. This got me going on all kinds of research, trial and error. All for nothing.

You see, I was going about this all wrong.

Thanks to some help from Julie Lerman (Entity Framework Guru and fellow Microsoft MVP) and Diego Vega (from the EF team at Microsoft), I found out that I could in fact run EF 6 and EF Core in the same project! All I needed to do (after getting all of the EF Core nuget packages all loaded up again) was create 2 DbContexts! One with EF Core for the Identity stuff. And one with EF6 for my application logic (so I can use the spatial features including DbGeography). At first, I had a some namespace confusion because there are classes with the same names in EF 6 and Core. But that was easily resolved.

It’s great when the solution is so simple.

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"?>
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,
    EntityFramework, Version=, 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()
                      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()
  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