LESSON 7 OF 20

7. SQL Server Connection, DbContext, and Migration Management

In this lesson, you will connect the ASP.NET Core MVC application to SQL Server, configure ApplicationDbContext, and apply Entity Framework Core migrations through a controlled development workflow.

75 dk 44

Introduction

In the previous lesson, we designed the content management application's data model with Entity Framework Core. Creating entity classes alone, however, is not enough. The application must connect that model to SQL Server, create the corresponding tables, and track schema changes over time.

In this lesson, we will connect the ASP.NET Core MVC application to SQL Server. We will configure the connection string, create the ApplicationDbContext class, register the SQL Server provider, and generate the first migration. We will then apply the migration to the database and inspect both the tables and Entity Framework Core's migration history.

This workflow is useful not only for creating the initial database, but also for evolving the schema as the application grows. Instead of deleting and recreating the database after every model change, we will make each change traceable and repeatable through source-controlled migration files.

1. Installing the required NuGet packages

We need the EF Core SQL Server provider to communicate with SQL Server. We can also install the Entity Framework Core command-line tool to create and apply migrations from a terminal. Run the following commands in the project directory:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 8.*
dotnet add package Microsoft.EntityFrameworkCore.Design --version 8.*
dotnet tool install --global dotnet-ef --version 8.*

If dotnet-ef is already installed, update it instead:

dotnet tool update --global dotnet-ef --version 8.*

Check that the project targets .NET 8 in the .csproj file:

<TargetFramework>net8.0</TargetFramework>

Keeping the major versions of the EF Core packages compatible with the target framework reduces design-time tooling problems.

2. Configuring the connection string

Rather than placing the connection string directly in Program.cs, store it in the configuration system. For local development, use appsettings.Development.json. The following example uses SQL Server LocalDB:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=CmsAppDb;Trusted_Connection=True;TrustServerCertificate=True;MultipleActiveResultSets=true"
  }
}

The DefaultConnection key under ConnectionStrings is significant because GetConnectionString("DefaultConnection") looks for that exact name. If you use SQL Server Express or a full SQL Server installation, replace the Server value with the name of your own instance.

Do not commit production passwords or sensitive connection details to source control. For local development, use User Secrets, environment variables, or a secure secret store. The example does not contain a password because it uses Windows authentication with LocalDB.

3. Creating the ApplicationDbContext class

A DbContext is the main working layer between entity classes and the database. It identifies which entities map to tables, how relationships are configured, and which provider receives the generated queries.

Create a Data folder in the project and add ApplicationDbContext.cs:

using Microsoft.EntityFrameworkCore;
using CmsApp.Models;

namespace CmsApp.Data;

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public DbSet<Article> Articles => Set<Article>();
}

In this example, Article is the entity created in the previous lesson. If your model is named Post or something else, update both the using statement and the DbSet declaration to match your project.

The DbSet<Article> property lets us query article records with LINQ and tells the migration system that an Articles table belongs to the model. You may also write the property explicitly:

public DbSet<Article> Articles { get; set; } = null!;

4. Registering the DbContext with dependency injection

Next, register the context in the application's service collection. Add the following code to Program.cs:

using CmsApp.Data;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection")
    ?? throw new InvalidOperationException(
        "The DefaultConnection connection string was not found.");

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));

builder.Services.AddControllersWithViews();

var app = builder.Build();

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

AddDbContext allows dependency injection to manage ApplicationDbContext instances. A controller can receive the context through its constructor:

using CmsApp.Data;
using Microsoft.AspNetCore.Mvc;

namespace CmsApp.Controllers;

public class ArticlesController : Controller
{
    private readonly ApplicationDbContext _context;

    public ArticlesController(ApplicationDbContext context)
    {
        _context = context;
    }

    public IActionResult Index()
    {
        var articles = _context.Articles.ToList();
        return View(articles);
    }
}

This example demonstrates the foundation of the controller pattern that we will expand in later lessons. Using dependency injection instead of constructing a context manually inside each method improves connection management and testability.

5. Creating the first migration

With the model and context ready, we can create a migration. A migration represents the difference between the current model and the database schema as code. In the terminal, navigate to the folder containing the project file and run:

dotnet ef migrations add InitialCreate

If the command succeeds, a Migrations folder will be created. It normally contains a migration class, a model snapshot, and metadata files. These files should be committed to source control because they describe how the database schema evolves.

Instead of editing migration files manually, change the entity classes or Fluent API configuration and create a new migration. Before applying it, inspect the generated operations. If a property was renamed, EF Core may interpret the change as dropping an old column and adding a new one rather than renaming the existing column.

6. Applying the migration to SQL Server

Apply the initial migration with the following command:

dotnet ef database update

The command uses the configured connection string to create the CmsAppDb database if necessary and execute the operations defined by the migration. You can inspect the result with SQL Server Object Explorer, SQL Server Management Studio, or Azure Data Studio.

In addition to the Articles table, you will normally see an __EFMigrationsHistory table. EF Core uses this table to record which migrations have already been applied. Running database update again will not execute migrations that are already recorded there.

To list the migrations known to the project, run:

dotnet ef migrations list

This helps you compare the migration files in the project with the migration history stored in the database.

7. Applying a model change in a controlled way

Suppose that you add a new property to the Article entity:

public class Article
{
    public int Id { get; set; }
    public string Title { get; set; } = string.Empty;
    public string Content { get; set; } = string.Empty;
    public bool IsPublished { get; set; }
}

Running database update immediately is not enough. First create a migration for the new model state:

dotnet ef migrations add AddArticlePublishingState

Open the generated migration and check that the expected operation is adding an IsPublished column to the Articles table. Then apply it:

dotnet ef database update

This two-step workflow is important because the model change, migration file, and database operation can each be reviewed. Use descriptive migration names such as AddArticlePublishingState instead of vague names like Update or NewMigration.

8. Generating SQL scripts and planning production changes

For local development, dotnet ef database update is convenient. In production, however, applying schema changes automatically when the application starts is not always appropriate. Generate a SQL script when you need to inspect or approve the SQL before deployment:

dotnet ef migrations script -o migration.sql

If different databases may be at different migration levels, create an idempotent script:

dotnet ef migrations script --idempotent -o migration-idempotent.sql

These scripts can be reviewed, archived, or applied by a database administrator during deployment. Always inspect migrations that remove columns, alter data types, or add required fields because they may cause data loss or require a data transformation step.

The command-line workflow is appropriate for local development and testing. For production, use a controlled deployment step, a reviewed SQL script, or a migration bundle. It is also safer to use a separate deployment identity with schema modification permissions rather than granting those permissions to the application's normal runtime identity.

9. Common mistakes

  • Mismatched connection string names: If the JSON uses DefaultConnection but the code requests AppConnection, the application will fail to find the connection string.
  • Running commands in the wrong directory: If dotnet ef cannot find the project file, use the --project option and, when necessary, the --startup-project option.
  • Missing the SQL Server provider: If UseSqlServer is unavailable, verify that Microsoft.EntityFrameworkCore.SqlServer is installed.
  • Deleting the database instead of using migrations: This may appear convenient during development, but it destroys existing data and does not test a realistic deployment workflow.
  • Applying a migration without reviewing it: Confirm that a renamed property was not translated into a column drop and a new column addition.
  • Mixing EnsureCreated with migrations: EnsureCreated bypasses migration history. Use one consistent migration-based schema management approach for this application.

10. Short practice exercise

Complete the following exercise:

  1. Create a Category entity with at least Id and Name properties.
  2. Add DbSet<Category> to ApplicationDbContext.
  3. Run dotnet ef migrations add AddCategories.
  4. Open the migration and verify that it creates a Categories table.
  5. Run dotnet ef database update and inspect the table in SQL Server.
  6. List the migrations and identify both InitialCreate and AddCategories.

Conclusion

In this lesson, we connected the ASP.NET Core MVC application to SQL Server, configured the connection string, and registered ApplicationDbContext with dependency injection. We then created and applied the first migration and learned how future model changes are transferred through additional migrations.

The application is now ready to work with a real database schema. In the next lessons, we will use this context in controllers to list, create, edit, and delete records. Keep migration files under source control, inspect schema changes before applying them, and treat database updates as an explicit part of the development and deployment process.

Sources