简体   繁体   English

在NHibernate中构造针对IUserType的查询

[英]Constructing query against IUserType in NHibernate

How can I construct a query against an custom IUserType field in NHibernate? 如何在NHibernate中针对自定义IUserType字段构造查询?

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. 我在数据库中有一个名为“State”的字段,其中包含一个表示给定对象所处状态的char。

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. 在我的代码中,我希望将其表示为枚举,因此我创建了一个带有每个状态值的枚举,并创建了一个IUserType,它将db的char值转换为我的枚举,然后返回选择和更新。

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. 大概是因为NHibernate不知道如何在给定StateEnum类型的情况下对DB的char字段进行选择。

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: NHibernate有3个用于枚举的内置映射器:

  • PersistentEnumType maps to an int column, and is not declared in the mapping. PersistentEnumType映射到int列,并且未在映射中声明。
  • EnumStringType maps to a varchar column. EnumStringType映射到varchar列。 The values are the ToString() values of the enum. 值是枚举的ToString()值。
  • EnumCharType maps to a char column. EnumCharType映射到char列。 The values are the result of (char) (int) enumvalue . 值是(char) (int) enumvalue

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM