Introduction

Entity Framework Core (EF Core) is a modern Object-Relational Mapper (ORM) for .NET developers.

It allows you to work with databases using C# classes instead of writing raw SQL queries.

With EF Core, you can perform CRUD operations (Create, Read, Update, Delete) quickly, making backend development easier and cleaner.

This guide explains how beginners can perform CRUD operations in just 10 minutes using EF Core.

Step 1: Prerequisites

Before starting, make sure you have:

  1. Visual Studio 2022 or VS Code

  2. .NET 6 or .NET 7 SDK

  3. SQL Server installed (or use SQL Server Express / LocalDB)

Step 2: Create a New ASP.NET Core Web API Project

Open terminal or Visual Studio:

  
    dotnet new webapi -n EfCoreDemo
cd EfCoreDemo
dotnet run
  

Step 3: Install EF Core Packages

Install EF Core and SQL Server provider:

  
    dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
  

Step 4: Create the Data Model

Create a folder Models and add Product.cs :

  
    namespace EfCoreDemo.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }
}
  

Step 5: Create the Database Context

Create Data/AppDbContext.cs :

  
    using Microsoft.EntityFrameworkCore;
using EfCoreDemo.Models;

namespace EfCoreDemo.Data
{
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options)
            : base(options) { }

        public DbSet<Product> Products { get; set; }
    }
}
  

Step 6: Configure Connection String

In appsettings.json , add:

  
    {
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=EfCoreDemoDB;Trusted_Connection=True;"
  },
  "AllowedHosts": "*"
}
  

Step 7: Register DbContext in Program.cs

  
    using Microsoft.EntityFrameworkCore;
using EfCoreDemo.Data;

var builder = WebApplication.CreateBuilder(args);

// Add DbContext
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
  

Step 8: Create the Database Using Migrations

  1. Add a migration:

  
    dotnet ef migrations add InitialCreate
  
  1. Apply migration:

  
    dotnet ef database update
  

Step 9: Create a CRUD Controller

Create Controllers/ProductsController.cs :

  
    using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using EfCoreDemo.Data;
using EfCoreDemo.Models;
using System.Collections.Generic;
using System.Threading.Tasks;

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

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

        // CREATE
        [HttpPost]
        public async Task<ActionResult<Product>> CreateProduct(Product product)
        {
            _context.Products.Add(product);
            await _context.SaveChangesAsync();
            return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
        }

        // READ ALL
        [HttpGet]
        public async Task<IEnumerable<Product>> GetProducts()
        {
            return await _context.Products.ToListAsync();
        }

        // READ ONE
        [HttpGet("{id}")]
        public async Task<ActionResult<Product>> GetProduct(int id)
        {
            var product = await _context.Products.FindAsync(id);
            if (product == null) return NotFound();
            return product;
        }

        // UPDATE
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateProduct(int id, Product product)
        {
            if (id != product.Id) return BadRequest();
            _context.Entry(product).State = EntityState.Modified;
            await _context.SaveChangesAsync();
            return NoContent();
        }

        // DELETE
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteProduct(int id)
        {
            var product = await _context.Products.FindAsync(id);
            if (product == null) return NotFound();
            _context.Products.Remove(product);
            await _context.SaveChangesAsync();
            return NoContent();
        }
    }
}
  

Key Points:

Step 10: Test the API

Use Swagger or Postman :

  1. GET /api/products – Fetch all products

  2. POST /api/products – Add a new product:

  
    {
  "name": "Laptop",
  "price": 45000
}
  
  1. PUT /api/products/1 – Update product

  2. DELETE /api/products/1 – Delete product

Advantages of Using EF Core

  1. No Raw SQL Needed – Work with C# classes instead of SQL.

  2. Cross-Database Support – Works with SQL Server, MySQL, PostgreSQL, and SQLite.

  3. Async Support – Makes applications fast and responsive.

  4. Migrations – Easy to manage database schema changes.

  5. LINQ Integration – Query database using C# LINQ syntax.

Conclusion

With EF Core , you can perform CRUD operations quickly and cleanly in ASP.NET Core:

Learning EF Core is essential for building full-stack applications with SQL Server and ASP.NET Core.

Once you master EF Core, you can combine it with Angular, React, or Vue to create full-stack projects with robust data management .