title: Mapping Enum as string in NHibernate 3.2 mapping by code
body: <p>Using NHibernate 3.2 mapping by code (not fluent-nhibernate), I'm trying to map an Enum field to a string column instead of the default int representation. I can't get the right syntax.</p>
  
  <p>For example:</p>
  
  <pre><code>    public class Account {
          public enum StateType { Pending, Active, Cancelled, Suspended }
          ...
          public virtual StateType State { get; set; }
          ...
      }</code></pre>
  
  <p>In the XML mapping, you can use <code>NHibernate.Type.EnumStringType</code> (see <a href="http://www.zvolkov.com/clog/2009/08/13/generic-enumstring-mapping-in-nhibernate-2-1/" rel="nofollow noreferrer">this link</a>), but how do I do it in mapping by code?</p>
  
  <pre><code>    NHibernate.Mapping.ByCode.ModelMapper mapper = new NHibernate.Mapping.ByCode.ModelMapper();
  
      mapper.Class&lt;Account&gt;(map => {
          map.Id(x => x.Id, attr => {
              attr.Column("id");
              attr.Generator(NHibernate.Mapping.ByCode.Generators.Identity);
          });
          // Default 'int' mapping
          //map.Property(x => x.State);
  
          // Cannot implicitly convert type 'StateType' to 'NHibernate.Type.EnumStringType'
          //map.Property&lt;NHibernate.Type.EnumStringType&lt;Account.StateType&gt;&gt;(x => x.State); 
  </code></pre>
  
  <p><strong>Update:</strong></p>
  
  <p>Using this mapping, I managed to get it to save as a string to the DB, but I now get an exception when loading from the DB to the object model.</p>
  
  <p><code>map.Property(x =&gt; x.State, attr =&gt; { attr.Type(NHibernateUtil.String); });</code></p>
  
  <p>This is the exception I get when trying to load the object:</p>
  
  <pre><code>Invalid Cast (check your mapping for property type mismatches); setter of Model.Account
  </code></pre>