Entity Framework  

Entity Framework Core for Beginners: CRUD in 10 Minutes

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
  
  • This creates a Web API project that can be used to perform CRUD operations.

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
  
  • These packages allow EF Core to work with SQL Server and create migrations.

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; }
    }
}
  
  • Id will be the primary key .

  • Name and Price are the product properties.

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; }
    }
}
  
  • DbSet<Product> represents the Products table in SQL Server.

Step 6: Configure Connection String

In appsettings.json , add:

  
    {
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=EfCoreDemoDB;Trusted_Connection=True;"
  },
  "AllowedHosts": "*"
}
  
  • EF Core will use this connection string to connect to SQL Server .

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();
  
  • EF Core is now ready to create and manage database tables .

Step 8: Create the Database Using Migrations

  1. Add a migration:

  
    dotnet ef migrations add InitialCreate
  
  • This generates a migration file that defines the database structure.

  1. Apply migration:

  
    dotnet ef database update
  
  • EF Core creates the EfCoreDemoDB database and the Products table .

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:

  • _context.Products represents the Products table .

  • Add , ToListAsync , FindAsync , Remove are EF Core CRUD methods .

  • SaveChangesAsync commits the changes to the database.

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:

  • Create : Add new records

  • Read : Fetch data from database

  • Update : Modify existing records

  • Delete : Remove records

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 .