Mapping Enum as string in NHibernate 3.2 mapping by code
Asked Answered
F

1

23

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
Fluoridation answered 29/8, 2011 at 17:42 Comment(0)
F
28

Got it! The following syntax works:

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

Fluoridation answered 1/9, 2011 at 18:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.