If you are forced to use an Anemic domain model, where do you put your business logic and calculated fields?

后端 未结 8 1572
南旧
南旧 2020-12-22 19:49

Our current O/RM tool does not really allow for rich domain models, so we are forced to utilize anemic (DTO) entities everywhere. This has worked fine, but I continue to st

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-22 19:57

    If your ORM technology only handles DTO objects well, that doesn't mean you have to throw out rich entity objects. You can still wrap your DTO objects with entity objects:

    public class MonkeyData
    {
       public string Name { get; set; }
       public List FavoriteFood { get; set; }
    }
    
    public interface IMonkeyRepository
    {
       Monkey GetMonkey(string name) // fetches DTO, uses entity constructor
       void SaveMonkey(Monkey monkey) // uses entity GetData(), stores DTO
    }
    
    
    public class Monkey
    {
       private readonly MonkeyData monkeyData;
    
       public Monkey(MonkeyData monkeyData)
       {
          this.monkeyData = monkeyData;
       }
    
       public Name { get { return this.monkeyData.Name; } }
    
       public bool IsYummy(Food food)
       {
          return this.monkeyData.FavoriteFood.Contains(food);
       }
    
       public MonkeyData GetData()
       {
          // CLONE the DTO here to avoid giving write access to the
          // entity innards without business rule enforcement
          return CloneData(this.monkeyData);
       }
    
    }
    

提交回复
热议问题