24

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
0

1 Answer 1

29

Got it! The following syntax works:

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.