问题描述
我对此进行了一些搜索,但没有发现任何内容.是否可以创建一个 Hibernate 查询来基于鉴别器返回一组对象?
I did some searching on this and didn't turn up anything. Is it possible to create a Hibernate query to return a set of objects based on a discriminator?
我有一个 AbstractUser 类,它由具体类 UserTypeA 和 UserTypeB 扩展.我正在使用每个层次结构表模型来映射我在 NHibernate 中的类,因此 UserTypeA 和 UserTypeB 都存储在具有不同鉴别器值的同一个表中.这是我的鉴别器映射属性:
I have an AbstractUser class which is extended by the concrete classes UserTypeA and UserTypeB. I'm using the table-per-hierarchy model to map my classes in NHibernate, so UserTypeA and UserTypeB are both stored in the same table with different discriminator values. Here is my discriminator mapping property:
<discriminator column="Type" type="string"/>
我的表中有一个列包含用户类型的名称.我想知道是否可以使用它运行 NHibernate 查询.
I have a column in my table that contains the name of the user type. I'm wondering if it's possible to run a NHibernate query using this.
我试过了:
public IList<DomainBase> FindByType(string typeName, Type type)
{
string query = "from " + type.Name + " k where k.Type = " + typeName;
return Session.CreateQuery(query).List<DomainBase>();
}
但由于 Type 实际上不是类的属性,只是表中的一列,这显然行不通.除非有一种方法可以将属性用作鉴别器,否则同时拥有用于此目的的属性和鉴别器似乎是多余的?
But since Type is not actually a property of the class, just a column in the table, this obviously doesn't work. It would seem redundant to have both a property for this purpose and a discriminator, unless there's a way to use a property as a discriminator?
推荐答案
实际上,这在 http://www.nhibernate.info/doc/nh/en/index.html#queryhql-where:
同样,特殊属性class
访问一个的鉴别器值多态情况下的实例坚持..Net 类名嵌入在 where 子句中转换为其鉴别器值.
from Eg.Cat cat where cat.class = Eg.DomesticCat
您还可以将 System.Type
实例作为参数传递.
You can also pass a System.Type
instance as a parameter.
这篇关于通过 NHibernate 中的鉴别器进行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!