Tutorials Entity Framework Core Tutorial
MediatR with EF Core
MediatR with EF Core: free step-by-step lesson with examples, common mistakes, and interview tips — part of Entity Framework Core Tutorial on Toolliyo Academy.
On this page
Entity Framework Core Tutorial · Lesson 73 of 100
MediatR with EF Core
Beginner ✓ → Intermediate ✓ → Advanced ✓ → Professional
Professional · 4 — Real projects · ~10 min · Module 8: Enterprise Architecture
What is this?
MediatR routes commands and queries to handlers — each handler injects ShopNestDbContext or repositories, keeping controllers thin.
Why should you care?
ShopNest API controllers should not grow 200-line checkout methods — PlaceOrderHandler encapsulates EF work testably.
See it live — copy this example
Paste into a .NET project with EF Core packages, then run with LocalDB/SQL Server (dotnet ef / dotnet run).
public record PlaceOrderCommand(int CustomerId, List<LineItem> Items) : IRequest<int>;
public class PlaceOrderHandler(ShopNestDbContext db) : IRequestHandler<PlaceOrderCommand, int>
{
public async Task<int> Handle(PlaceOrderCommand cmd, CancellationToken ct)
{
var order = new Order { CustomerId = cmd.CustomerId };
foreach (var line in cmd.Items)
order.Items.Add(new OrderItem { ProductId = line.ProductId, Quantity = line.Qty, UnitPrice = line.Price });
db.Orders.Add(order);
await db.SaveChangesAsync(ct);
return order.Id;
}
}
// Program.cs: builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(...));
What happened?
- Controller sends command via IMediator.
- Handler owns EF transaction logic.
- One class per use case simplifies testing and discovery.
Practice next
- Install MediatR and register assembly scanning.
- Create one handler per command/query touching EF.
- Inject DbContext or UnitOfWork into handlers.
- Add ValidationBehavior validating PlaceOrderCommand before handler runs.
- Return Result
instead of raw int for error propagation.
Remember
MediatR dispatches to EF-backed handlers. Controllers stay thin Send() calls. Handlers align with use cases.
ShopNest checkout handler
POST /orders sends PlaceOrderCommand; handler persists via EF.
Outcome: Checkout logic tested in isolation with InMemory or SQLite.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!