DDD - Entity state transition

后端 未结 3 1719
小鲜肉
小鲜肉 2021-02-09 01:57

consider the following simplified example:

public class Ticket
{
   public int Id;
   public TicketState State;

   public Ticket()
   {
      // from where do I         


        
3条回答
  •  闹比i
    闹比i (楼主)
    2021-02-09 02:27

    To me, a simple key-value pair that represents state in the database (or whatever persistence medium) doesn't need to be modeled as such in the domain. In the domain, I would make TicketState an enum, and make it the responsibility of the ITicketRepository to know how to map that to the requirements of the database schema.

    Within the ticket repository, you can have a cache of ticket state IDs keyed on TicketState, that is lazy-loaded into a static variable (just one approach) from the database. The ticket repository would map the Ticket.State value to IDs from that cache for inserts/updates.

    namespace Domain {
      public class Ticket {
        public Ticket() { State = TicketStates.New; }
        public void Finish() { State = TicketStates.Finished; }
        public TicketStates State {get;set;}
      }
    
      public enum TicketState { New, Finished }
    }
    
    namespace Repositories {
      public class SqlTicketRepository : ITicketRepository {
        public void Save(Ticket ticket) {
          using (var tx = new TransactionScope()) { // or whatever unit of work mechanism
            int newStateId = TicketStateIds[ticket.State];
            // update Ticket table with newStateId
          }
        }
      }
    
      private Dictionary _ticketStateIds;
      protected Dictionary TicketStateIds{
        get {
          if (_ticketStateIds== null) 
            InitializeTicketStateIds();
          return _ticketStateIds;
        }
      }
    
      private void InitializeTicketStateIds() {
        // execute SQL to get all key-values pairs from TicketStateValues table
        // use hard-coded mapping from strings to enum to populate _ticketStateIds;
      }
    }
    

提交回复
热议问题