title: EntityFramework DatabaseGenerated.Identity and AutoMapper == null ID key
body: <p>I am using EF and AutoMapper with Azure table storage emulation.</p>
  
  <p>I have two types, Fragment (serializable DTO) and FragmentEntity (EF persisted DO). I use AutoMapper to map from the DTO to the DO for persistence on a PUT call and vice versa on a GET call.</p>
  
  <p>The problem is my inexperience with both EF and AutoMapper. I have configured the FragmentEntity class (according to the documentation I can find) to be generating the Id for the Fragment at the database (see below).</p>
  
  <p>Entity ID definition:</p>
  
  <pre><code> [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public int? Id { get; set; }
  </code></pre>
  
  <p>At runtime the http client makes a REST PUT call with the new content (Fragment). This is received via WCF and serialized into a Fragment as follows.</p>
  
  <pre><code> [OperationContract]
   [WebInvoke(UriTemplate = "/Fragments", Method = "PUT")]
   void PutFagment(Fragment fragment);
  </code></pre>
  
  <p>During debugging if I step over the code the received ID value is null (as I have defined the ID property as optional).</p>
  
  <pre><code> public void PutFagment(Fragment fragment)
   {
        var fragmentEntity = Mapper.Map&lt;Fragment, FragmentEntity&gt;(fragment);
        _fragmentContext.Add(fragmentEntity);
   }
  
   [DataMember]
   public virtual int? Id { get; set; }
  </code></pre>
  
  <p>I am not sure if defining it as optional was a wise move; I did this because if it is not optional the value defaults to zero which automapper then maps to the target FragmentEntity and subsequently all keys end up being zero (clearly wrong) in the database.</p>
  
  <p>As you may expect I have also made the FragmentEntity Id optional to avoid setting a value in the application code, my hope was if it was null the database generation may occur however this doesn't appear to be happening.</p>
  
  <pre><code>&lt;Fragment&gt;&lt;Id i:nil="true"/&gt;&lt;Name&gt;Drei&lt;/Name&gt;&lt;Type&gt;3&lt;/Type&gt;&lt;/Fragment&gt;
  </code></pre>
  
  <p>My problems:</p>
  
  <ol>
  <li>I think the decision to make Id optional in both classes is incorrect, I assume there is some AutoMapper configuration which will appropriately handle this case and that both can remain non-optional.</li>
  <li>I am not sure why the DatabaseGenerated attribute is not taking effect.</li>
  </ol>