
Entities Shouldn't Be Data Bags: The Anemic Domain Model Problem
- كاتب موثّق
محتويات المقال
order.Lines.Add(gift) and saves. It passed review and its tests. A week later finance finds shipped orders with new lines, and totals that no longer match those lines. The rule "no changes after payment" was there all along, in OrderService.AddLine, which also recalculates the total. The new endpoint just never called it, and nothing in Order could stop it.
The common misconception
OrderService, PricingService, ShippingService. Keeping data and logic apart is clean separation of concerns.
What actually happens
It looks like a domain model
Rules in services are rules you can skip
Services still exist, but thin
EF Core doesn't need public setters
IReadOnlyCollection<T> backed by a private List<T>, with EF Core reading and writing the field. The database mapping lives in the persistence layer, so the entity stays a plain C# class.
The fix: let the entity guard its own rules
public sealed class Order{ public OrderStatus Status { get; set; } public List<OrderLine> Lines { get; set; } = []; public decimal Total { get; set; }}public sealed class OrderService{ public void AddLine(Order order, OrderLine line) { if (order.Status != OrderStatus.Draft) throw new InvalidOperationException("Order is locked"); order.Lines.Add(line); order.Total = order.Lines.Sum(l => l.Price * l.Quantity); }}// The gift endpoint skips the service: order.Lines.Add(gift) compilespublic sealed class Order{ private readonly List<OrderLine> _lines = []; public OrderStatus Status { get; private set; } = OrderStatus.Draft; public IReadOnlyCollection<OrderLine> Lines => _lines; public decimal Total => _lines.Sum(l => l.Price * l.Quantity); public void AddLine(OrderLine line) { if (Status != OrderStatus.Draft) throw new InvalidOperationException("Order is locked"); _lines.Add(line); } public void Ship() { if (Status != OrderStatus.Paid) throw new InvalidOperationException("Only paid orders ship"); Status = OrderStatus.Shipped; }}order.AddLine(gift), and it throws for a paid order. order.Lines.Add(...) no longer compiles, Status can't be set from outside, and the total can't drift because it's derived from the lines. The service shrinks to loading the order, calling a method and saving. Each new entry point gets the rules for free.
How to apply it in your project
Pick one entity with real rules Start where bugs cluster, such as orders, payments or bookings. List every rule about it that lives in a service, a controller or a validator. Move each rule into a named method Name methods after business operations, such as AddLine,PayorShip, notSetStatus. Each one checks its rule and changes state only when the rule holds.Close the setters Use private set, derive values like totals instead of storing them in the object, and expose collections asIReadOnlyCollection<T>backed by a private field that EF Core maps.Thin the services Leave loading, saving, transactions and calls to other systems in the service. If a service method still contains an ifabout business state, ask whether the entity should own it.
Key takeaways
An anemic model has the shape of a domain model without its behavior: all the mapping cost, none of the protection. A rule in a service holds only for callers that use that service; a rule in the entity holds for everyone. Services coordinate, entities decide; Evans's application layer is deliberately thin. EF Core supports private setters and read-only collections, so persistence is no excuse for public setters. Plain data entities are fine for simple CRUD; choose rich entities where rules are many and keep changing.
📚 المصادر
AnemicDomainModel — Martin Fowler, bliki (2003) Design a microservice domain model — .NET Microservices Architecture, Microsoft Learn Design validations in the domain model layer — .NET Microservices Architecture, Microsoft Learn Implement the infrastructure persistence layer with Entity Framework Core — .NET Microservices Architecture, Microsoft Learn
التعليقات (0)