title: DDD: Entity identity before being persisted
body: <p>In Domain Driven Design, one of the defining characteristic of an Entity is that it has an identity.</p>
  
  <p><strong>Problem:</strong></p>
  
  <p>I am not able to provide a unique identity to Entities on instance creation.  This identity is only provided by the repository once the entity is persisted (this value is provided from the underlying database).</p>
  
  <p>I cannot begin to use <code>Guid</code> values at this point.  The existing data is stored with <code>int</code> primary key values and I cannot generate a unique int on instantiation.</p>
  
  <p><strong>My solution:</strong></p>
  
  <ul>
  <li>Each Entity has an identity value</li>
  <li>The identity is only set to a real identity once persisted (provided by the database)</li>
  <li>The identity is set to default when instantiated before persistence</li>
  <li>If the identity is default, entities are comparable through reference</li>
  <li>If the identity is not default, entities are comparable through identity values</li>
  </ul>
  
  <p><strong>Code (the abstract base class for all entities):</strong></p>
  
  <pre><code>public abstract class Entity&lt;IdType&gt;
  {
      private readonly IdType uniqueId;
  
      public IdType Id
      {
          get 
          { 
              return uniqueId; 
          }
      }
  
      public Entity()
      {
          uniqueId = default(IdType);
      }
  
      public Entity(IdType id)
      {
          if (object.Equals(id, default(IdType)))
          {
              throw new ArgumentException("The Id of a Domain Model cannot be the default value");
          }
  
          uniqueId = id;
      }
  
      public override bool Equals(object obj)
      {
          if (uniqueId.Equals(default(IdType)))
          { 
              var entity = obj as Entity&lt;IdType&gt;;
  
              if (entity != null)
              {
                  return uniqueId.Equals(entity.Id);
              }
          }
  
          return base.Equals(obj);
      }
  
      public override int GetHashCode()
      {
          return uniqueId.GetHashCode();
      }
  }
  </code></pre>
  
  <p><strong>Question:</strong></p>
  
  <ul>
  <li>Would you consider this to be a good alternative to generating Guid values on instance creation?</li>
  <li>Are there better solutions out there for this problem?</li>
  </ul>