(EF Core) Configuring Visual Studio for Database Migration

We shall start by creating a simple asp.net core project. Then we shall add nuget packages for a database such as Microsoft SQL Server. After that we shall add a very rudimentary, basic model class, and a DbContext class for specifying the connection string to the built-in SQL Server Express of Visual Studio. Finally, we shall use the package manager console to add the command line tools for ef core migrations.

Categories | About |     |  

Parveen,

Step 1 - Create a simple ASP.NET Core Project

Migrations is a feature of EF Core. Therefore, any project that uses EF Core can be used for this tutorial. But since we are learning ASP.NET Core - so we shall use an ASP.NET Core project for this walkthrough.

Start by creating any simple visual studio project on asp.net core. There is no need to add any razor pages because we will be working on the database side.

Let us open the program.cs file. We have added bare minimum code: no services have been configured, the application maps a get request, and responds with a message.

// NOTE: we have used Visual Studio 2022 
// so the "Main" function is implied 
// If you are on Visual Studio 2019 then put 
// the code in the Main of the Program class 

// namespaces 
using Microsoft.AspNetCore.Builder;

using Microsoft.AspNetCore.Hosting;

using Microsoft.AspNetCore.Http;

using Microsoft.Extensions.DependencyInjection;

using Microsoft.Extensions.Hosting;

Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder =>
{

  webBuilder.ConfigureServices(services =>
  {

    // services can be added 
    // for razor pages, dbcontext etc., 
  });

  webBuilder.Configure(app =>
  {

    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {

      endpoints.MapGet ("/", async context =>
      {

        await context.Response.WriteAsync("Hello Migration!");

      }

      );

    });

  });

})

.Build()
.Run();

Video Explanation

Please watch the following youtube video:

Step 2 - Add Packages for SQL Server

We shall be using the built-in SQL Server Express for this tutorial - because Visual Studio provides a SQL Object Explorer for conveniently viewing a database and its tables.

So let us add nuget packages for SQL Server connectivity.

Use the Tools menu to open the package manager console. Type the command Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 5.0.13 to get the EF Core nuget packages for SQL Server.

PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 5.0.13

Hit enter and let the installation complete to success.

Step 3 - Add a DbContext

Add a model class to your project. This model class shall translate to a table in our database.

public class Blog
{

  [Key]
  public int ID { get; set; }

  // any string type property 
  public String? Heading { get; set; }
}

Next add a DbContext class.

This class must have a default constructor. Otherwise migrations will not succeed.

Migration tools are design time tools. They need a default constructor in your DbContext class. This means that we should not use the parameterized constructor for DbContextOptionsBuilder. We have to, therefore, override the OnConfiguring method.

public class BlogContext : DbContext
{

  protected override void OnConfiguring(
    DbContextOptionsBuilder optionsBuilder)
  {

    SqlConnectionStringBuilder connectionStringBuilder
        = new SqlConnectionStringBuilder()
        {
            InitialCatalog = "db_blog",
            DataSource = @"(localdb)\MSSQLLocalDB",
            IntegratedSecurity = true
        };

    optionsBuilder.UseSqlServer(connectionStringBuilder.ConnectionString);

  }

  public DbSet<Blog>? Blogs { get; set; }
}

The connection string can be set with the classic SqlConnectionStringBuilder. It makes the conenction string more readable.

The name of our database shall be db_blog and it shall contain a table called Blog.

Finally - Add Packages for EF Core Tools

The migration feature requires a command line tool from EF Core.

This tool can be obtained through a nuget package.

Use the package manager console to add nuget packages for entity framework tools.

PM> Install-Package Microsoft.EntityFrameworkCore.Tools -Version 5.0.13

Allow the process to complete successfully.

Now our project is configured for Migrations. In the next tutorial we shall create our database by executing our first database migration.


This Blog Post/Article "(EF Core) Configuring Visual Studio for Database Migration" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.