Tutorials Entity Framework Core Tutorial
Domain Layer with EF Core
Domain Layer 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 76 of 100
Domain Layer with EF Core
Beginner ✓ → Intermediate ✓ → Advanced ✓ → Professional
Professional · 4 — Real projects · ~10 min · Module 8: Enterprise Architecture
What is this?
Domain layer holds entities, value objects, enums, and domain events — no EF attributes required if mapping stays in Infrastructure Fluent API.
Why should you care?
ShopNest Product.IsEligibleForDiscount() belongs in Domain — not in DbContext or controller — persistence ignorance keeps model pure.
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 class Order
{
public int Id { get; private set; }
public int CustomerId { get; private set; }
private readonly List<OrderItem> _items = new();
public IReadOnlyCollection<OrderItem> Items => _items;
public void AddItem(Product product, int qty)
{
if (qty <= 0) throw new DomainException("Quantity must be positive.");
if (product.StockQty < qty) throw new DomainException("Insufficient stock.");
_items.Add(new OrderItem(product.Id, qty, product.Price));
}
}
What happened?
- Order encapsulates invariants in AddItem.
- Private setter and backing list prevent invalid states.
- EF maps via Fluent API ignoring domain methods.
Practice next
- Remove EF attributes from Domain entities if using Fluent exclusively.
- Use factory methods and behavior methods not public setters everywhere.
- Raise domain events on state changes if adopting DDD events.
- Add Money value object for Price instead of raw decimal.
- Configure backing field _items in Fluent for Order.Items mapping.
Remember
Domain encodes business rules. No EF dependency in Domain project. Infrastructure maps private setters via Fluent.
ShopNest rich order model
AddItem enforces stock rules before EF ever sees OrderItem rows.
Outcome: Invalid orders fail in domain tests without database.
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!