views:

211

answers:

1

How can I construct a query against an custom IUserType field in NHibernate?

More specifically: I'm working on a brownfield application. I have a field in the database called "State" which contains a char representing what state a given object is in.

In my code I want this to be represented as an enum so I've created an enum with a value for each state and created an IUserType that converts from the db's char value to my enum and back for selects & updates.

I want to construct a query that looks something like this:

session.CreateCriteria<MyType>().Add(Expression.Eq("State", StateEnum.Complete))

However, that query throws an exception:

could not resolve property: State of: MyNamespace.MyType

presumably because NHibernate doesn't know how to do a select against the DB's char field given a StateEnum type.

+2  A: 

Your class and mapping should be something like the following:

class MyType
{
    public virtual StateEnum State { get; set; }
}

<class name="MyType">
    <property name="State" type="MyNamespace.MyEnumUserType, MyDll" />
</class>

NHibernate has 3 built in mappers for enum:

  • PersistentEnumType maps to an int column, and is not declared in the mapping.
  • EnumStringType maps to a varchar column. The values are the ToString() values of the enum.
  • EnumCharType maps to a char column. The values are the result of (char) (int) enumvalue.
Lachlan Roche
Turned out to be a mistype in my config but you do have it right
statichippo