.NET  

CRUD Operations in ASP.NET Core with Entity Framework – Real-World Example

Real-Time Example. Customer Service API with ASP.NET Core & EF Core

You want to manage Customer records with typical operations:

  • Create customer records

  • Get all customers or by ID

  • Update customer details

  • Delete customer records

Step-by-step implementation

1. Create Project

dotnet new webapi -n CustomerServiceApi
cd CustomerServiceApi

2. Define Customer Model

Create Models/Customer.cs

namespace CustomerServiceApi.Models
{
    public class Customer
    {
        public int Id { get; set; }
        public string FullName { get; set; } = string.Empty;
        public string Email { get; set; } = string.Empty;
        public string PhoneNumber { get; set; } = string.Empty;
        public DateTime RegisteredAt { get; set; } = DateTime.UtcNow;
    }
}

3. Setup DbContext

Create Data/AppDbContext.cs

using Microsoft.EntityFrameworkCore;
using CustomerServiceApi.Models;

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

        public DbSet<Customer> Customers { get; set; }
    }
}

4. Configure EF Core and Services in Program.cs

using CustomerServiceApi.Data;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

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

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

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

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

app.Run();

Add connection string in appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=CustomerServiceDb;Trusted_Connection=True;TrustServerCertificate=True;"
  }
}

5. Create CustomersController

Create Controllers/CustomersController.cs

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

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

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

        // GET: api/customers
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Customer>>> GetCustomers()
        {
            return await _context.Customers.ToListAsync();
        }

        // GET: api/customers/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Customer>> GetCustomer(int id)
        {
            var customer = await _context.Customers.FindAsync(id);
            if (customer == null) return NotFound();
            return customer;
        }

        // POST: api/customers
        [HttpPost]
        public async Task<ActionResult<Customer>> CreateCustomer(Customer customer)
        {
            _context.Customers.Add(customer);
            await _context.SaveChangesAsync();
            return CreatedAtAction(nameof(GetCustomer), new { id = customer.Id }, customer);
        }

        // PUT: api/customers/5
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateCustomer(int id, Customer customer)
        {
            if (id != customer.Id) return BadRequest();

            _context.Entry(customer).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!_context.Customers.Any(c => c.Id == id))
                    return NotFound();
                else throw;
            }

            return NoContent();
        }

        // DELETE: api/customers/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteCustomer(int id)
        {
            var customer = await _context.Customers.FindAsync(id);
            if (customer == null) return NotFound();

            _context.Customers.Remove(customer);
            await _context.SaveChangesAsync();

            return NoContent();
        }
    }
}

6. Run EF Core Migration

Install EF CLI if needed

dotnet tool install --global dotnet-ef

Create and apply migration

dotnet ef migrations add InitialCreate
dotnet ef database update

7. Run and Test

dotnet run

Go to: https://localhost:5001/swagger

Test your Customer API endpoints with Swagger UI:

  • GET /api/customers

  • POST /api/customers

  • GET /api/customers/{id}

  • PUT /api/customers/{id}

  • DELETE /api/customers/{id}

Summary

You now have a real-time Customer Service REST API managing customer records with full CRUD using Entity Framework Core in ASP.NET Core. This can be extended with authentication, paging, validation, etc.

If you want, I can help with those next! Would you like that?