DDD, value objects and ORM

前端 未结 5 1957
情书的邮戳
情书的邮戳 2020-12-14 09:56

Value objects do not have identity. ORM needs identity to update the database.

How to trick ORM?

(Marking Id for value object as internal won\'t work bec

5条回答
  •  难免孤独
    2020-12-14 10:45

    You have 2 options:

    • Save the Value Object in the same Aggregate Root table
    • Separate table using the Aggregate Root as the ID

    For your example, something like:

    public class Customer : Entity
    {
        public Guid CustomerID { get; }
        public string LastName { get; set; }
        public Address HomeAddress { get; set; }
    }
    
    public class Address : ValueObject
    {
        public string Street { get; set; }
        public string City { get; set; }
        public string ZipCode { get; set; }
    }
    

    Option 1 (Pseudo-SQL):

    ​CREATE​ ​TABLE​ Customer (
          // aggregate root
    ​     customerId ​int​ ​NOT​ ​NULL​,
          lastName VARCHAR(30),
    
          // value object
          street VARCHAR(100),
          city VARCHAR(50),
          zip VARCHAR(10)
    ​     ​CONSTRAINT​ PK_Customer ​PRIMARY​ ​KEY​ (customerId)
    ​   )
    

    Option 2 (Pseudo-SQL):

    // aggregate root
    CREATE​ ​TABLE​ Customer (
    ​   customerId ​int​ ​NOT​ ​NULL​,
        lastName VARCHAR(30)
        CONSTRAINT​ PK_Customer ​PRIMARY​ ​KEY​ (customerId)
        )
    
    // value object
    CREATE​ ​TABLE​ Address (     
    ​     customerId ​int​ ​NOT​ ​NULL​, // same ID from Customer
    
    ​     street VARCHAR(100),
          city VARCHAR(50),
          zip VARCHAR(10)
          ​CONSTRAINT​ PK_Address ​PRIMARY​ ​KEY​ (customerId)
        )
    
    • Then you can create a toDomain(sqlResult) function to convert the query result in your domain object
    • Try to use one-table approach by default

提交回复
热议问题