title: Persisting immutable objects to a relational database
body: <p>I've seen certain object-oriented experts advise that domain objects (POCOs) should be immutable.</p>
  
  <p>That is, their state should be entirely determined at construction, and changes to state should require creating a completely new instance.</p>
  
  <p>But say I'm persisting to a relational DB using an ORM - how do I determine which properties to persist, and how do I reconstruct the domain object based on data in a database?</p>
  
  <p>For example, say I want to write this object to the database:</p>
  
  <pre><code>class User
  {
      private string _emailAddress;
  
      public User(string emailAddress, string password)
      {
         // ... generate hash &amp; seed
         _emailAddress = emailAddress;
      }
  
      public string PasswordHash { get; private set; }
  
      public string PasswordSeed { get; private set; }
  
      public bool ValidatePassword(string password)
      {
         // validate it against the stored hash
      }
  }
  </code></pre>
  
  <p>In the example above, I want to store the state of the object and retrieve it later. This means storing the PasswordHash, PasswordSeed and EmailAddress.</p>
  
  <p>But the structure of the class prevents me from doing so.</p>
  
  <ul>
  <li><p>PasswordHash and PasswordSeed - I can store them, but what happens when I want to read them back from the database and reconstruct the object? There's no constructor parameters to pass them to, and I can't even construct the object without them because 'password' must be supplied and I don't know what the original password was. I can't set the 'PasswordHash' or 'PasswordSeed' properties, because they're 'private set'.</p></li>
  <li><p>EmailAddress - I can't store it because even though it's part of the object state, it's marked private and can't be accessed internally.</p></li>
  </ul>
  
  <p>Yes, I could just make every property in the object public and read/write. But then, where's my encapsulation and immutability?</p>
  
  <p>See, I wanted to store the password as a hash/seed and hide the emailaddress for a reason. I wanted to enforce a certain workflow into my domain objects.</p>
  
  <p>But when it comes to storing them, I have to undo all those constraints and turn my domain objects into dumb key/value stores, with no constraints.</p>
  
  <hr>
  
  <p>The underlying problem, it seems, is that relational databases have no concept of encapsulation. Every column in a table is 'public' and every value is 'mutable'.</p>
  
  <p>So does this mean I have to throw out relational mapping altogether if I'm to have an immutable domain model? Or is there some well-known strategy for getting around this that I just don't know about yet?</p>