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
Join the conversation! Your thoughts help the community grow.