الانتقال إلى المحتوى
Software ArchitectureDDD· 7 دقائق للقراءة

Entities Shouldn't Be Data Bags: The Anemic Domain Model Problem

A rule kept in a service holds only for callers that go through that service. Put the rules in the entity that owns the data, and let services coordinate.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
محتويات المقال

Support added a "goodwill gift" button last sprint. The endpoint loads the order, calls 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

The belief: entities are data. They should be plain classes with public properties that mirror the tables, and business rules belong in service classes: OrderService, PricingService, ShippingService. Keeping data and logic apart is clean separation of concerns.

It's an easy belief to pick up. Scaffolding tools and many tutorials generate entities as property bags, and older versions of Entity Framework required collections that any caller could add to. Many experienced designers recommend a service layer on top of the domain model, and Fowler notes that this causes confusion. And for a simple CRUD service, Microsoft's .NET microservices guide says plain data entities aren't an anti-pattern at all.

The half-truth: services have a real job, and simple CRUD doesn't need rich entities. But once the rules are many and keep changing, moving them out of the entities leaves the data unguarded.

What actually happens

It looks like a domain model

Fowler's description of the starts with how convincing it looks: objects "named after the nouns in the domain space", connected with real relationships. The catch is "that there is hardly any behavior on these objects, making them little more than bags of getters and setters." A set of service objects "capture all the domain logic, carrying out all the computation and updating the model objects with the results." His verdict on the cost: anemic models "incur all of the costs of a domain model, without yielding any of the benefits." You still map objects to tables, and what you get back is procedural code, a set of Transaction Scripts.

Rules in services are rules you can skip

Microsoft's guide states the alternative plainly: "Domain entities must implement behavior in addition to implementing data attributes," and "The entity's methods take care of the invariants and rules of the entity instead of having those rules spread across the application layer." Its validation chapter adds that "Domain entities should always be valid entities," because "many bugs occur because objects are in a state they should never have been in."

With public setters, an holds only where someone remembered to call the service. Every new entry point, such as an admin endpoint, a background job, a message handler or a data fix, has to rediscover the rule. When the entity enforces it, there's no path around it.

Services still exist, but thin

A rich model doesn't remove services. Fowler quotes Eric Evans on the application layer: it "is kept thin. It does not contain business rules or knowledge, but only coordinates tasks and delegates work to collaborations of domain objects in the next layer down." Loading the order, saving it and sending the confirmation email are coordination. Deciding whether a line can be added is a business rule. Fowler also stresses that this doesn't mix persistence into the domain: the logic in a domain object is "domain logic - validations, calculations, business rules".

EF Core doesn't need public setters

The ORM argument is mostly history. Microsoft's guide notes that since EF Core 1.1 entities can use plain fields and private property setters, and a collection can be exposed as 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

C#
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) compiles

Now the gift endpoint has only one way in, 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.

MythReality
Entities are data; rules go in servicesMicrosoft: entities implement behavior, and their methods guard the invariants
A service layer means entities without behaviorEvans: the application layer is thin and delegates to domain objects
Rich entities mix persistence into the domainFowler: domain objects hold domain logic; persistence stays in its own layer
EF Core needs public settersSince EF Core 1.1: private setters, fields, and read-only collections backed by fields
Anemic models are always wrongFor a simple CRUD service, Microsoft says they're not an anti-pattern

How to apply it in your project

  1. Pick one entity with real rulesStart where bugs cluster, such as orders, payments or bookings. List every rule about it that lives in a service, a controller or a validator.
  2. Move each rule into a named methodName methods after business operations, such as AddLine, Pay or Ship, not SetStatus. Each one checks its rule and changes state only when the rule holds.
  3. Close the settersUse private set, derive values like totals instead of storing them in the object, and expose collections as IReadOnlyCollection<T> backed by a private field that EF Core maps.
  4. Thin the servicesLeave loading, saving, transactions and calls to other systems in the service. If a service method still contains an if about 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.

📚 المصادر

  1. AnemicDomainModel — Martin Fowler, bliki (2003)
  2. Design a microservice domain model — .NET Microservices Architecture, Microsoft Learn
  3. Design validations in the domain model layer — .NET Microservices Architecture, Microsoft Learn
  4. Implement the infrastructure persistence layer with Entity Framework Core — .NET Microservices Architecture, Microsoft Learn

التعليقات (0)