Fluent with Enumerations.

Currently investigating the usage of nHibernate (fluently) as an ORM to be used within our software. First impressions are that I like it a lot. I feel that we should have made this move a long time ago but sometimes with the  time constraints its not always feasible to stray from well trodden paths… Currently flying at plenty of new tech though so expect plenty of postings!

Whilst putting together my first sample classes I came across a small gotcha whilst defining my LogonClass and retrieving the associated data. Code snippets follow:-

First off my Model:-

public class ContactLogOnModel {
        public virtual int Id { get; set; }

        [Required]
        [Display(Name = “User Name”)]
        public virtual string LogOnName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = “Password”)]
        public virtual string LogOnPassword { get; set; }

        [Required]
        public virtual LogOnContext LogOnContext { get; set; }

        public virtual ContactModel Contact { get; set; }

    }

Quickly followed by my defintiion of the LogOnContext enumeration:-

        public enum LogOnContext :int{
            None=0,
            Executive=1,
            CompanySecretary=2,
            Bureau=4,
            Broker=8,
            God=16
        }
And finally as I am using the fluent interface I need to also include my simple mapping file:-

        public class ContactLogOnMap:ClassMap<ContactLogOnModel> {
            public ContactLogOnMap() {
                Table(“ContactLogOn”);
                Id(x => x.Id).Column(“ContactLogonID”);
                Map(x => x.LogOnContext);
                Map(x => x.LogOnName);
                Map(x => x.LogOnPassword);
            }
        }

Wow, so that was nice simple and painless.. run it up and when calling GetAll on my repository…..

Capture

At first I must admit to that age old response of first swearing, followed by not reading the error message at all as it doesn’t make sense right?! Except it does… 16 is the enumerated value for ‘God’ within the LogOnContext. So it appears that fluent nHibernate appears not to support enumerations out of the box, which is fine…,  as a a quick trawl of the internet revealed the simple solution which required  a small addition to the mapping class detail in bold and underlined:-

        public class ContactLogOnMap:ClassMap<ContactLogOnModel> {
            public ContactLogOnMap() {
                Table(“ContactLogOn”);
                Id(x => x.Id).Column(“ContactLogonID”);
                Map(x => x.LogOnContext).CustomType(typeof(LogOnContext));
                Map(x => x.LogOnName);
                Map(x => x.LogOnPassword);
            }
        }

A quick recompile and away you go onto the next headscratcher.