Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping Enum as string in NHibernate 3.2 mapping by code

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.

For example:

    public class Account {
        public enum StateType { Pending, Active, Cancelled, Suspended }
        ...
        public virtual StateType State { get; set; }
        ...
    }

In the XML mapping, you can use NHibernate.Type.EnumStringType (see this link), but how do I do it in mapping by code?

    NHibernate.Mapping.ByCode.ModelMapper mapper = new NHibernate.Mapping.ByCode.ModelMapper();

    mapper.Class<Account>(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<NHibernate.Type.EnumStringType<Account.StateType>>(x => x.State); 

Update:

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.

map.Property(x => x.State, attr => { attr.Type(NHibernateUtil.String); });

This is the exception I get when trying to load the object:

Invalid Cast (check your mapping for property type mismatches); setter of Model.Account
like image 677
dstj Avatar asked Aug 29 '11 17:08

dstj


People also ask

What is NHibernate mapping?

NHibernate is an object–relational mapping (ORM) solution for the Microsoft . NET platform. It provides a framework for mapping an object-oriented domain model to a traditional relational database.

What is the difference between NHibernate and fluent NHibernate?

Fluent NHibernate offers an alternative to NHibernate's standard XML mapping files. Rather than writing XML documents, you write mappings in strongly typed C# code. This allows for easy refactoring, improved readability and more concise code.


1 Answers

Got it! The following syntax works:

map.Property(x => x.State, attr => attr.Type<NHibernate.Type.EnumStringType<Account.StateType>>());

like image 170
dstj Avatar answered Dec 06 '22 18:12

dstj