Introduction
In full-stack development, your backend application needs to communicate with a database to store, retrieve, and manage data.
ASP.NET Core makes it easy to connect to SQL Server, one of the most popular relational databases.
This article explains step by step how beginners can connect ASP.NET Core to SQL Server, set up the database, and perform basic operations.
Step 1: Prerequisites
Before starting, make sure you have:
Visual Studio 2022 or VS Code installed.
SQL Server installed (Express or full version).
.NET 6 or .NET 7 SDK installed.
Step 2: Create a New ASP.NET Core Web API Project
Open a terminal or Visual Studio:
dotnet new webapi -n SqlServerDemo
cd SqlServerDemo
dotnet run
This creates a Web API project.
By default, it runs on
https://localhost:5001.
Step 3: Install Entity Framework Core Packages
Entity Framework Core (EF Core) is an ORM that helps your application interact with SQL Server without writing raw SQL queries.
Install these packages using NuGet Package Manager or dotnet CLI:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore– Core EF library.Microsoft.EntityFrameworkCore.SqlServer– SQL Server provider.Microsoft.EntityFrameworkCore.Tools– For migrations and database updates.
Step 4: Create the Data Model
Create a folder Models and a class User.cs:
namespace SqlServerDemo.Models
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
}
Each property represents a column in the database table.
Step 5: Create the Database Context
Create a folder Data and a class AppDbContext.cs:
using Microsoft.EntityFrameworkCore;
using SqlServerDemo.Models;
namespace SqlServerDemo.Data
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<User> Users { get; set; }
}
}
DbSet<User>represents the Users table in SQL Server.DbContextmanages database connections and operations.
Step 6: Configure Connection String
In appsettings.json, add a connection string:
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=SqlServerDemoDB;Trusted_Connection=True;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Server=localhost– SQL Server instance.Database=SqlServerDemoDB– Name of the database. EF Core will create it if it does not exist.Trusted_Connection=True– Uses Windows authentication.

Join the conversation! Your thoughts help the community grow.