Final project: a notes API with EF Core, DI and logging
Course contents (16 lessons)
- The type system
- Records, structs and value equality
- Interfaces and abstract classes
- Generics and constraints
- Delegates, events and lambdas
- Querying and matching data
- LINQ in depth: deferred execution, grouping and joins
- IEnumerable versus IQueryable
- Pattern matching in modern C#
- Async and await: how Task really works
- Async patterns: cancellation, timeouts and async streams
- Application structure
- Dependency injection and service lifetimes
- Configuration, options and logging
- Data and web
- Entity Framework Core basics: DbContext, migrations and queries
- Building a minimal API with ASP.NET Core
- Unit testing with xunit
- Performance and the final project
- Performance basics: Span of T and fewer allocations
- Final project: a notes API with EF Core, DI and logging
The goal
This project ties the course together. We build a small notes API. It stores notes in SQLite through EF Core, exposes JSON endpoints with a minimal API, uses a service class registered with dependency injection, reads a setting through the options pattern, and logs what it does. It is small enough to read in one sitting, and every piece has been covered in an earlier lesson.
Create the project and add the package:
dotnet new web -n NotesApi
cd NotesApi
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
The design
I split the code into four small pieces, so each has one job.
- Entity and DTOs.
Noteis the database row.NoteDtoandSaveNoteRequestare what the API sends and receives. The entity never leaves the service. - NotesDbContext. The EF Core mapping.
- NoteService. The business rules: validation, trimming, limits. It depends on the context, the options and a logger.
- Endpoints. They translate HTTP to service calls and back.
Here is the whole program.
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<NotesOptions>(builder.Configuration.GetSection("Notes"));
builder.Services.AddDbContext<NotesDbContext>(o =>
o.UseSqlite(builder.Configuration.GetConnectionString("Notes") ?? "Data Source=notes.db"));
builder.Services.AddScoped<NoteService>();
var app = builder.Build();
// For the project we create the database at startup; use migrations in a real deployment
using (var scope = app.Services.CreateScope())
{
await scope.ServiceProvider.GetRequiredService<NotesDbContext>().Database.EnsureCreatedAsync();
}
var notes = app.MapGroup("/notes");
notes.MapGet("/", async (NoteService service, string? search, CancellationToken ct) =>
TypedResults.Ok(await service.ListAsync(search, ct)));
notes.MapGet("/{id:int}", async (int id, NoteService service, CancellationToken ct) =>
await service.GetAsync(id, ct) is NoteDto note
? Results.Ok(note)
: Results.NotFound());
notes.MapPost("/", async (SaveNoteRequest request, NoteService service, CancellationToken ct) =>
{
var (note, error) = await service.CreateAsync(request, ct);
return note is null
? Results.ValidationProblem(new Dictionary<string, string[]> { ["note"] = [error!] })
: Results.Created($"/notes/{note.Id}", note);
});
notes.MapDelete("/{id:int}", async (int id, NoteService service, CancellationToken ct) =>
await service.DeleteAsync(id, ct) ? Results.NoContent() : Results.NotFound());
app.Run();
public class NotesOptions
{
public int MaxTitleLength { get; set; } = 80;
public int MaxBodyLength { get; set; } = 2000;
}
public class Note
{
public int Id { get; set; }
public string Title { get; set; } = "";
public string Body { get; set; } = "";
public DateTime CreatedUtc { get; set; }
public DateTime UpdatedUtc { get; set; }
}
public record NoteDto(int Id, string Title, string Body, DateTime CreatedUtc, DateTime UpdatedUtc);
public record SaveNoteRequest(string Title, string Body);
public class NotesDbContext(DbContextOptions<NotesDbContext> options) : DbContext(options)
{
public DbSet<Note> Notes => Set<Note>();
protected override void OnModelCreating(ModelBuilder model)
{
model.Entity<Note>().Property(n => n.Title).HasMaxLength(200).IsRequired();
}
}
public class NoteService(NotesDbContext db, IOptions<NotesOptions> options, ILogger<NoteService> logger)
{
private readonly NotesOptions _limits = options.Value;
public async Task<List<NoteDto>> ListAsync(string? search, CancellationToken ct)
{
IQueryable<Note> query = db.Notes.AsNoTracking();
if (!string.IsNullOrWhiteSpace(search))
{
query = query.Where(n => n.Title.Contains(search));
}
return await query
.OrderByDescending(n => n.UpdatedUtc)
.Select(n => new NoteDto(n.Id, n.Title, n.Body, n.CreatedUtc, n.UpdatedUtc))
.ToListAsync(ct);
}
public async Task<NoteDto?> GetAsync(int id, CancellationToken ct) =>
await db.Notes.AsNoTracking()
.Where(n => n.Id == id)
.Select(n => new NoteDto(n.Id, n.Title, n.Body, n.CreatedUtc, n.UpdatedUtc))
.FirstOrDefaultAsync(ct);
public async Task<(NoteDto? Note, string? Error)> CreateAsync(SaveNoteRequest request, CancellationToken ct)
{
string? error = Validate(request);
if (error is not null) return (null, error);
var now = DateTime.UtcNow;
var note = new Note
{
Title = request.Title.Trim(),
Body = request.Body.Trim(),
CreatedUtc = now,
UpdatedUtc = now
};
db.Notes.Add(note);
await db.SaveChangesAsync(ct);
logger.LogInformation("Created note {NoteId}", note.Id);
return (ToDto(note), null);
}
public async Task<bool> DeleteAsync(int id, CancellationToken ct)
{
int rows = await db.Notes.Where(n => n.Id == id).ExecuteDeleteAsync(ct);
if (rows > 0) logger.LogInformation("Deleted note {NoteId}", id);
return rows > 0;
}
private string? Validate(SaveNoteRequest request)
{
if (string.IsNullOrWhiteSpace(request.Title)) return "Title is required.";
if (request.Title.Trim().Length > _limits.MaxTitleLength)
return $"Title must be at most {_limits.MaxTitleLength} characters.";
if ((request.Body ?? "").Length > _limits.MaxBodyLength)
return $"Body must be at most {_limits.MaxBodyLength} characters.";
return null;
}
private static NoteDto ToDto(Note n) => new(n.Id, n.Title, n.Body, n.CreatedUtc, n.UpdatedUtc);
}
Walking through it
The setup is at the top. Options are bound from the Notes configuration section, so you can change limits in appsettings.json or an environment variable such as Notes__MaxTitleLength. AddDbContext registers the context as scoped, one per request, which is what we want. The connection string comes from configuration with a fallback for local use. The service is scoped too, because it depends on the scoped context. Registering it as a singleton would be the captive dependency bug from the DI lesson.
Every handler accepts a CancellationToken and passes it into the service, which passes it to EF Core. If the client disconnects, the query stops.
The service returns a tuple with either a note or an error message. That keeps validation failures out of exception handling, in the spirit of the Result type from the generics lesson. For a larger project, I would replace the tuple with a proper result type.
Reads use AsNoTracking and project straight into NoteDto inside the query, so the database sends only the needed columns. The search filter builds on an IQueryable and is translated to SQL LIKE. Delete uses ExecuteDeleteAsync and checks how many rows it removed. That saves a load-then-delete round trip.
Testing it
The service is easy to unit test, because its dependencies come in through the constructor. For tests, create a context with an in-memory SQLite connection (Data Source=:memory: with an open connection) rather than the EF Core in-memory provider. SQLite behaves much more like a real database, including constraints and query translation. For end-to-end tests of the endpoints, the Microsoft.AspNetCore.Mvc.Testing package provides WebApplicationFactory. You will need to make the Program class visible to the test project, for example with a public partial class Program { } declaration at the bottom of the file.
Where to take it next
- Replace
EnsureCreatedwith real migrations. - Add paging to the list endpoint with
SkipandTake. - Write a test project covering the service with xUnit, using the clock pattern from the testing lesson.
Common mistakes
- Exposing the entity from the API. A later column becomes public by accident.
- Registering the service as singleton while it uses a scoped context.
- Skipping validation because "the client already checks". Clients can be bypassed.
Try it yourself
- Run the API and use
curlto create, list, fetch and delete a note. - Add an update endpoint,
PUT /notes/{id}, with a matchingUpdateAsyncin the service that reusesValidate. - Add an
appsettings.jsonwith a smallMaxTitleLengthand confirm that longer titles are rejected. - Write three unit tests for
NoteServicevalidation using SQLite in memory.
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<NotesOptions>(builder.Configuration.GetSection("Notes"));
builder.Services.AddDbContext<NotesDbContext>(o =>
o.UseSqlite(builder.Configuration.GetConnectionString("Notes") ?? "Data Source=notes.db"));
builder.Services.AddScoped<NoteService>();
var app = builder.Build();
// For the project we create the database at startup; use migrations in a real deployment
using (var scope = app.Services.CreateScope())
{
await scope.ServiceProvider.GetRequiredService<NotesDbContext>().Database.EnsureCreatedAsync();
}
var notes = app.MapGroup("/notes");
notes.MapGet("/", async (NoteService service, string? search, CancellationToken ct) =>
TypedResults.Ok(await service.ListAsync(search, ct)));
notes.MapGet("/{id:int}", async (int id, NoteService service, CancellationToken ct) =>
await service.GetAsync(id, ct) is NoteDto note
? Results.Ok(note)
: Results.NotFound());
notes.MapPost("/", async (SaveNoteRequest request, NoteService service, CancellationToken ct) =>
{
var (note, error) = await service.CreateAsync(request, ct);
return note is null
? Results.ValidationProblem(new Dictionary<string, string[]> { ["note"] = [error!] })
: Results.Created($"/notes/{note.Id}", note);
});
notes.MapDelete("/{id:int}", async (int id, NoteService service, CancellationToken ct) =>
await service.DeleteAsync(id, ct) ? Results.NoContent() : Results.NotFound());
app.Run();
public class NotesOptions
{
public int MaxTitleLength { get; set; } = 80;
public int MaxBodyLength { get; set; } = 2000;
}
public class Note
{
public int Id { get; set; }
public string Title { get; set; } = "";
public string Body { get; set; } = "";
public DateTime CreatedUtc { get; set; }
public DateTime UpdatedUtc { get; set; }
}
public record NoteDto(int Id, string Title, string Body, DateTime CreatedUtc, DateTime UpdatedUtc);
public record SaveNoteRequest(string Title, string Body);
public class NotesDbContext(DbContextOptions<NotesDbContext> options) : DbContext(options)
{
public DbSet<Note> Notes => Set<Note>();
protected override void OnModelCreating(ModelBuilder model)
{
model.Entity<Note>().Property(n => n.Title).HasMaxLength(200).IsRequired();
}
}
public class NoteService(NotesDbContext db, IOptions<NotesOptions> options, ILogger<NoteService> logger)
{
private readonly NotesOptions _limits = options.Value;
public async Task<List<NoteDto>> ListAsync(string? search, CancellationToken ct)
{
IQueryable<Note> query = db.Notes.AsNoTracking();
if (!string.IsNullOrWhiteSpace(search))
{
query = query.Where(n => n.Title.Contains(search));
}
return await query
.OrderByDescending(n => n.UpdatedUtc)
.Select(n => new NoteDto(n.Id, n.Title, n.Body, n.CreatedUtc, n.UpdatedUtc))
.ToListAsync(ct);
}
public async Task<NoteDto?> GetAsync(int id, CancellationToken ct) =>
await db.Notes.AsNoTracking()
.Where(n => n.Id == id)
.Select(n => new NoteDto(n.Id, n.Title, n.Body, n.CreatedUtc, n.UpdatedUtc))
.FirstOrDefaultAsync(ct);
public async Task<(NoteDto? Note, string? Error)> CreateAsync(SaveNoteRequest request, CancellationToken ct)
{
string? error = Validate(request);
if (error is not null) return (null, error);
var now = DateTime.UtcNow;
var note = new Note
{
Title = request.Title.Trim(),
Body = request.Body.Trim(),
CreatedUtc = now,
UpdatedUtc = now
};
db.Notes.Add(note);
await db.SaveChangesAsync(ct);
logger.LogInformation("Created note {NoteId}", note.Id);
return (ToDto(note), null);
}
public async Task<bool> DeleteAsync(int id, CancellationToken ct)
{
int rows = await db.Notes.Where(n => n.Id == id).ExecuteDeleteAsync(ct);
if (rows > 0) logger.LogInformation("Deleted note {NoteId}", id);
return rows > 0;
}
private string? Validate(SaveNoteRequest request)
{
if (string.IsNullOrWhiteSpace(request.Title)) return "Title is required.";
if (request.Title.Trim().Length > _limits.MaxTitleLength)
return $"Title must be at most {_limits.MaxTitleLength} characters.";
if ((request.Body ?? "").Length > _limits.MaxBodyLength)
return $"Body must be at most {_limits.MaxBodyLength} characters.";
return null;
}
private static NoteDto ToDto(Note n) => new(n.Id, n.Title, n.Body, n.CreatedUtc, n.UpdatedUtc);
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account