How to connect ASP.NET Core Web API to SQL Server using Entity Framework Core step by step

How to Connect ASP.NET Core Web API to SQL Server Using Entity Framework Core (Step-by-Step Guide)

In this tutorial, you will learn:

Prerequisites for ASP.NET Core to Web API SQL Server

Create ASP.NET Core Web API to SQL Server Project

Step 1: Open Visual Studio

Step 2: Select Template

Step 3: Configure Project

Step 4: Run Project

Install Packages for ASP.NET Core Web API SQL Server

dotnet add package Microsoft.EntityFrameworkCore --version 8.0.0
dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 8.0.0
dotnet add package Microsoft.EntityFrameworkCore.Tools --version 8.0.0

Configure SQL Server for ASP.NET Core Web API SQL Server

"ConnectionStrings": {
  "DefaultConnection": "Server=YOUR_SERVER_NAME;Database=StudentDB;Trusted_Connection=True;TrustServerCertificate=True;"
}
"Server=(localdb)\\MSSQLLocalDB;Database=StudentDB;Trusted_Connection=True;"

Create Model in ASP.NET Core Web API (SQL Server)

Step 1: Create Models Folder

Step 2: Create Student Model

namespace StudentApi.Models
{
    public class Student
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string Email { get; set; }
    }
}

Explanation

Create DbContext in ASP.NET Core Web API (SQL Server)

What is DbContext?

Step 1: Create Data Folder

Step 2: Create AppDbContext Class

using Microsoft.EntityFrameworkCore;
using StudentApi.Models;namespace StudentApi.Data
{
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options)
            : base(options)
        {
        }        public DbSet<Student> Students { get; set; }
    }
}

Explanation

Register DbContext in Program.cs

using Microsoft.EntityFrameworkCore;
using StudentApi.Data;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container
builder.Services.AddControllers();

// Register DbContext with SQL Server
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(
        builder.Configuration.GetConnectionString("DefaultConnection")));

// Swagger configuration
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure middleware
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthorization();

app.MapControllers();

app.Run();

Explanation

Step 2: Create Database Using EF Core

dotnet ef migrations add InitialCreate 
dotnet ef database update

What happens here?

Step 3: Create CRUD Controller

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using StudentApi.Data;
using StudentApi.Models;

namespace StudentApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class StudentsController : ControllerBase
    {
        private readonly AppDbContext _context;

        public StudentsController(AppDbContext context)
        {
            _context = context;
        }

        [HttpGet]
        public async Task<IActionResult> GetAll()
        {
            return Ok(await _context.Students.ToListAsync());
        }

        [HttpGet("{id}")]
        public async Task<IActionResult> GetById(int id)
        {
            var student = await _context.Students.FindAsync(id);
            if (student == null) return NotFound();
            return Ok(student);
        }

        [HttpPost]
        public async Task<IActionResult> Create(Student student)
        {
            _context.Students.Add(student);
            await _context.SaveChangesAsync();
            return Ok(student);
        }

        [HttpPut("{id}")]
        public async Task<IActionResult> Update(int id, Student student)
        {
            var existing = await _context.Students.FindAsync(id);
            if (existing == null) return NotFound();

            existing.Name = student.Name;
            existing.Email = student.Email;

            await _context.SaveChangesAsync();
            return Ok(existing);
        }

        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(int id)
        {
            var student = await _context.Students.FindAsync(id);
            if (student == null) return NotFound();

            _context.Students.Remove(student);
            await _context.SaveChangesAsync();

            return Ok("Deleted successfully");
        }
    }
}

How This Controller Works

Operations performed:

Step 4: Run and Test API

dotnet run
https://localhost:<port>/swagger

Test the endpoints:

ASP.NET Core Web API to SQL Server Swagger UI showing CRUD API endpoints
SQL Server Students table data generated from ASP.NET Core Web API using Entity Framework Core

Common Error: Identity Column Issue (VERY IMPORTANT)

{
  "id": 1,
  "name": "John",
  "email": "john@gmail.com"
}
{
  "name": "John",
  "email": "john@gmail.com"
}

Why this happens

Best Practices

Final Tip

Conclusion

Related Articles

Leave a Comment

Your email address will not be published. Required fields are marked *