C# Corner

Entity Framework Core Migrations

Today I'm going to cover how to do Entity Framework Core migrations in a .NET Core application through the command line and in code. To get started create a new .NET Core Console Application as seen in Figure 1.

Figure 1: Create a New .NET Core Console App
[Click on image for larger view.] Figure 1: Create a New .NET Core Console App

Next install the SQL Server Entity Framework Core NuGet package as seen in Figure 2.

Figure 2: Install EF Core Tools NuGet Package
[Click on image for larger view.] Figure 2: Install EF Core Tools NuGet Package

We also need to install the Microsoft.EntityFrameworkCore.Tools NuGet package as seen in Figure 3.

Figure 2: Install EF Core SQL NuGet Package
[Click on image for larger view.] Figure 3: Install EF Core SQL NuGet Package

Now create a new folder in your project named Models. Then create a Person class under the Models folder as seen in Listing 1.

Listing 1: Person Model Class

using System;
using System.Collections.Generic;
using System.Text;

namespace VSMEFMigrationsDemo.Models
{
  public class Person
  {
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
  }
}

Next we create the AppContext class that is a custom DbContext that will allow access to Person records as seen in Listing 2.

Listing 2: AppContext Class

using Microsoft.EntityFrameworkCore;
using VSMEFMigrationsDemo.Models;

namespace VSMEFMigrationsDemo
{
  public class AppContext : DbContext
  {
    private const string ConnectionString = "Server=(localdb)\\mssqllocaldb;Database=EFCore;Trusted_Connection=True;";

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
      optionsBuilder.UseSqlServer(ConnectionString);
    }

    public DbSet<Person> Persons { get; set; }
  }
}

Now it is time to create our initial migration through the NuGet Package Manager Console. Enter the command "Add-Migration InitialCreate" without the quotes. Now you can update the database by either running "Update-Database" from the NuGet Package Manager Console or by running context.Database.Migrate(). To use the later update your Program.cs class to look like Listing 3.

Listing 3: Database Migration in Code

using System;
using Microsoft.EntityFrameworkCore;

namespace VSMEFMigrationsDemo
{
  class Program
  {
    static void Main(string[] args)
    {
      using (var context = new AppContext())
      {
        context.Database.Migrate();
        Console.WriteLine("Database has been migrated");
      }

      Console.ReadLine();
    }
  }
}

The application should run successfully and you should see "Database has been migrated" output through the console as seen in Figure 4.

Figure 4: Running the First Migration
[Click on image for larger view.] Figure 4: Running the First Migration

Now you can add make tweaks to your model classes run "Add-Migration migration_name" from the NuGet Package Manager and the app will automatically update the database when it runs. To test this out let's add an Email field to the Person model then add a migration and run the app. Your update Person class should look like Listing 4 now.

Listing 4: Updated Person Class

using System;
using System.Collections.Generic;
using System.Text;

namespace VSMEFMigrationsDemo.Models
{
  public class Person
  {
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
  }
}

Then create a new migration by running "Add-Migration PersonAddedEmail" from the NuGet Package Manger. Now we'll update the program to test out the change. Update the Program class to look like Listing 5.

Listing 5: Updated Program to Test Migration

using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using VSMEFMigrationsDemo.Models;

namespace VSMEFMigrationsDemo
{
  class Program
  {
    static void Main(string[] args)
    {
      using (var context = new AppContext())
      {
        context.Database.Migrate();
        Console.WriteLine("Database has been migrated");

        var newPerson = new Person()
        {
          Email = "[email protected]",
          FirstName = "Eric",
          LastName = "Vogel"
        };
        context.Persons.Add(newPerson);

        context.SaveChanges();

        var existingPerson = context.Persons.Single(x => x.Id == 1);
        Console.WriteLine("Email was set to: " + existingPerson.Email);
      }

      Console.ReadLine();
    }
  }
}

Run the program and you will see that the Email field was indeed added to the Persons table and can be accessed as seen in Figure 5.

Figure 5: Completed Demo Program
[Click on image for larger view.] Figure 5: Completed Demo Program

Today I've shown you how to create a simple .NET Core application that can update its own database at run-time. As you can see this is very powerful. If you prefer to run the migration ahead of time you can script it through Visual Studio or the command line (run "dotnet ef database update"). Furthermore if your DBAs insist you can generate a SQL script for them to run by running either "Script-Migration" from the NuGet Package Manager Console or "dotnet ef migrations script" from the command line.

Note: You can get the code download for this application by clicking on the "GET CODE DOWNLOAD" button right below my byline at the beginning of this article.

About the Author

Eric Vogel is a Senior Software Developer for Red Cedar Solutions Group in Okemos, Michigan. He is the president of the Greater Lansing User Group for .NET. Eric enjoys learning about software architecture and craftsmanship, and is always looking for ways to create more robust and testable applications. Contact him at [email protected].

comments powered by Disqus

Featured

  • Full Stack Hands-On Development with .NET

    In the fast-paced realm of modern software development, proficiency across a full stack of technologies is not just beneficial, it's essential. Microsoft has an entire stack of open source development components in its .NET platform (formerly known as .NET Core) that can be used to build an end-to-end set of applications.

  • .NET-Centric Uno Platform Debuts 'Single Project' for 9 Targets

    "We've reduced the complexity of project files and eliminated the need for explicit NuGet package references, separate project libraries, or 'shared' projects."

  • Creating Reactive Applications in .NET

    In modern applications, data is being retrieved in asynchronous, real-time streams, as traditional pull requests where the clients asks for data from the server are becoming a thing of the past.

  • AI for GitHub Collaboration? Maybe Not So Much

    No doubt GitHub Copilot has been a boon for developers, but AI might not be the best tool for collaboration, according to developers weighing in on a recent social media post from the GitHub team.

  • Visual Studio 2022 Getting VS Code 'Command Palette' Equivalent

    As any Visual Studio Code user knows, the editor's command palette is a powerful tool for getting things done quickly, without having to navigate through menus and dialogs. Now, we learn how an equivalent is coming for Microsoft's flagship Visual Studio IDE, invoked by the same familiar Ctrl+Shift+P keyboard shortcut.

Subscribe on YouTube