Connecting ASP.NET Core MVC to SQL Server using EF Core.
This part will teach you how to:
Configure SQL Server connection
Create DbContext
Create database using EF Core migrations
Replace in-memory repository with real SQL database
Use async EF Core CRUD operations
Let’s begin.
Getting Started With ASP.NET Core MVC – Part 3
Connecting to SQL Server Using Entity Framework Core
1. Install EF Core Packages
Open Package Manager Console:
Install-Package Microsoft.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
2. Add Connection String
Open appsettings.json and add:
"ConnectionStrings": {
"DefaultConnection": "Server=YOUR_SERVER_NAME;Database=MVCAppDB;Trusted_Connection=True;MultipleActiveResultSets=true"
}
Examples:
If using SQL Express:
Server=.\\SQLEXPRESS;Database=MVCAppDB;Trusted_Connection=True;
If using SQL Server authentication:
Server=localhost;Database=MVCAppDB;User Id=sa;Password=YourPassword123;
3. Create ApplicationDbContext
Create folder Data → file ApplicationDbContext.cs:
using Microsoft.EntityFrameworkCore;
using MVCApp.Models;
namespace MVCApp.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Product> Products { get; set; }
}
}
✔ This DbContext represents your database.
4. Register EF Core in Program.cs
Open Program.cs:
using MVCApp.Data;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
// Register DbContext
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
var app = builder.Build();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Product}/{action=Index}/{id?}");
app.Run();
5. Enable EF Core Migrations
Open Package Manager Console:
Add-Migration InitialCreate
Output should say "Build succeeded."
Then:
Update-Database
✔ This creates the database and the Products table.
6. Remove Old In-Memory Repository
Delete/ignore your previous custom repository (ProductRepository).
Now your actual database will store products.
7. Update ProductController to Use EF Core
Open ProductController.cs:

Join the conversation! Your thoughts help the community grow.