Entity Framework Core Beginner

DbContext and connecting to SQL Server

Before EF Core can talk to SQL Server it needs a connection string, a provider and a DbContext registered with dependency injection. This lesson sets all three up in an MVC app and explains why a DbContext lives for exactly one request.

From connection string to a query
  1. Startappsettings.jsonHolds ConnectionStrings:DefaultConnection
  2. Step 2Program.csAddDbContext<ShopContext> with UseSqlServer(...)
  3. Step 3A request arrivesDI creates one ShopContext for this request
  4. Step 4Controller uses itConstructor injection gives the controller the context
  5. Step 5Queries and savesThe context opens connections only when needed
  6. EndRequest endsThe context is disposed automatically

The idea in plain words

Install the provider package for your database, for example Microsoft.EntityFrameworkCore.SqlServer. Put the connection string in configuration rather than code, then register your DbContext in Program.cs. ASP.NET Core then hands a fresh context to every controller that asks for one.

AddDbContext registers the context with a scoped lifetime, meaning one instance per HTTP request. That is exactly what you want: a DbContext is cheap to create, keeps track of the entities it loaded, and is not safe to share between threads.

Example: configuration and registration

C#
// appsettings.json
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=ShopDb;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

// Program.cs
builder.Services.AddDbContext<ShopContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

Example: using it in a controller

C#
public class ProductsController : Controller
{
    private readonly ShopContext _db;

    public ProductsController(ShopContext db) => _db = db;

    public async Task<IActionResult> Index()
        => View(await _db.Products.AsNoTracking().OrderBy(p => p.Name).ToListAsync());
}

In Visual Studio 2026

Visual Studio makes the setup point and click.

  • Right-click the project, choose Manage NuGet Packages, open Browse and install Microsoft.EntityFrameworkCore.SqlServer and Microsoft.EntityFrameworkCore.Tools.
  • SQL Server Express LocalDB is installed with the ASP.NET and web development workload, so the (localdb)\mssqllocaldb connection string works without installing SQL Server.
  • Open View, SQL Server Object Explorer to browse LocalDB databases, see tables and run queries after migrations create the database.

Common mistakes

  • Hard-coding the connection string or committing production passwords. Use user secrets in development and environment variables or a vault in production.
  • Registering the context as a singleton, or storing it in a static field.
  • Running two queries in parallel on the same context with Task.WhenAll, which throws.
  • Creating a context with new in controllers instead of using dependency injection.

Interview question

Why is DbContext registered as scoped in ASP.NET Core?

A DbContext holds a change tracker and a connection and is not thread-safe, so it should not be shared across concurrent requests (singleton), yet creating one per injection (transient) could give different parts of the same request different contexts and lose tracked changes. Scoped gives one instance per HTTP request, shared by the controller and services in that request, and disposed at the end.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.