Enum Parse error

Topics: Troubleshooting
May 24, 2013 at 8:50 AM
Edited May 24, 2013 at 8:50 AM
Hi,

I've a parse error when i try to use an enum for a property in my record class.
[DataContract]
public class ContactRecord
{
    [DataMember]
    public virtual int Id { get; set; }

    [DataMember]
    public virtual string Email { get; set; }

    [DataMember]        
    public virtual EStatut Statut { get; set; }
}
public enum EStatut : int
    {
        Ok = 1,
        Ko = 0
    }
When i load my records from database with

_repository.Table.ToList()

i have a nhibernateexception can't parse 0 as EStatut.

if i replace the enum by an int, everything works.

Any idea ?
May 24, 2013 at 12:24 PM
Edited May 24, 2013 at 12:26 PM
I found a way to do it.

The simplest way would be to use an enum as string but i don't want to store string values for my status in the database.

I finally solved my problem using FluentHibernate mapping override.

I kept my Statut Property mapped as in into the database as int and i created another property with my Enum Type.
using FluentNHibernate.Mapping;
using FluentNHibernate.Automapping.Alterations;
using FluentNHibernate.Automapping;
..
public class ContactRecordMappingOverride : IAutoMappingOverride<ContactRecord>
    {
        public void Override(AutoMapping<ContactRecord> mapping)
        {
            mapping.IgnoreProperty(p => p.EStatut);
        }
    }
In order to make it work,you must tell Fluent to use your override class.

You can do it with the following code
AutoMap.AssemblyOf<ContactRecord>().UseOverridesFromAssemblyOf<ContactRecordMappingOverride>();
I decided to place this code at the load event of my module using Autofac.Module
http://stackoverflow.com/questions/8561770/orchard-module-loading-event
public class MyModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            AutoMap.AssemblyOf<ContactRecord>().UseOverridesFromAssemblyOf<ContactRecordMappingOverride>();
        }
    }
https://github.com/jagregory/fluent-nhibernate/wiki/Auto-mapping
    [DataContract]
    public class ContactRecord
    {
        [DataMember]
        public virtual int Statut { get; set; }

       [DataMember]
        public virtual EStatut EStatut
        {
            get
            {
                EStatut st = .EStatut.Inconnu;

                Enum.TryParse<.EStatut>(this.Statut.ToString(), out st);

                return st;
            }
            set
            {
                try
                {
                    this.Statut = (int)value;
                }
                catch (Exception ex)
                {
                }
            }
        }
May 24, 2013 at 8:31 PM
That's complicated,.
I simply store enum as int in the DB, having an int member in the PartRecord class and the real enum in the Part class, converting in each get/set between record and part.