Building a request to IUserType in NHibernate

How can I create a query for a custom IUserType field in NHibernate?

More specifically: I am working on a brown box application. I have a field in the database called "State" that contains a char representing what state this object is in.

In my code, I want this to be represented as an enumeration, so I created an enumeration with a value for each state and created an IUserType that converts from the db char value to my enum and back for selection and updating.

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

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

However, this request throws an exception:

 could not resolve property: State of: MyNamespace.MyType 

presumably because NHibernate does not know how to make a choice regarding the DB char field specified for the StateEnum type.

+6
c # nhibernate
source share
1 answer

Your class and collation should look something like this:

 class MyType { public virtual StateEnum State { get; set; } } <class name="MyType"> <property name="State" type="MyNamespace.MyEnumUserType, MyDll" /> </class> 

NHibernate has 3 built-in modules for listing:

  • PersistentEnumType is displayed in the int column and is not declared in the mapping.
  • EnumStringType is displayed in the varchar column. The values ​​represent the values ​​of the ToString () enumeration.
  • EnumCharType is displayed in the char column. Values ​​are the result of (char) (int) enumvalue .
+6
source share

All Articles