[英]How to map native SQL query result to a list of custom value types in NHibernate?
I have a value type called FiscalYear
which essentially is a wrapper for an integer. 我有一个称为
FiscalYear
的值类型,它实际上是一个整数的包装器。 I have also implemented the NHibernate.UserTypes.IUserType
for it. 我还为它实现了
NHibernate.UserTypes.IUserType
。 Now I can map properties of type FiscalYear
directly to SQL Types and NHibernate will convert them automatically. 现在,我可以将
FiscalYear
类型的FiscalYear
直接映射到SQL Types,NHibernate会自动将它们转换。
It all works fine. 一切正常。 But now I would like to perform a native SQL query to get a list of fiscal years from the database.
但是现在我想执行一个本机SQL查询,以从数据库中获取会计年度的列表。 Here is the current code:
这是当前代码:
public IEnumerable<FiscalYear> FiscalYears
{
get
{
var result = new List<FiscalYear>();
foreach (var fiscalYear in Session.CreateSQLQuery(FiscalYearsQuery).List<Int16>())
{
result.Add(new FiscalYear(fiscalYear));
}
return result;
}
}
Is works, but my question is: since I have already implemented the IUserType
for FiscalYear
, is it possible to simplify this code to something like this: 是
IUserType
,但我的问题是:由于我已经为FiscalYear
实现了FiscalYear
,是否可以将这段代码简化为如下所示:
public IEnumerable<FiscalYear> FiscalYears
{
get
{
return Session
.CreateSQLQuery(FiscalYearsQuery)
.List<FiscalYear>();
}
}
Unfortunately this doesn't work. 不幸的是,这不起作用。 Using
Transformers.AliasToBean
doesn't help either, since FiscalYear
is a value type and not an entity. 使用
Transformers.AliasToBean
也无济于事,因为FiscalYear
是值类型而不是实体。
I think this is really something that should be easy to do, but all my attempts so far failed. 我认为这确实应该很容易做到,但是到目前为止我的所有尝试都失败了。 I guess I'm just missing something out?
我想我只是错过了什么?
When you use CreateSQLQuery
you must add the types of the returning values, i have never used native sql queries with custom types, but you can try: 当您使用
CreateSQLQuery
,必须添加返回值的类型,但我从未使用过具有自定义类型的本机sql查询,但是您可以尝试:
return Session
.CreateSQLQuery(FiscalYearsQuery)
.AddScalar("*QueryColumnName*", FiscalYear)
.List<FiscalYear>();
If this not works you can implement IResultTransformer
for more elegant way to convert your data. 如果这不起作用,则可以实现
IResultTransformer
以更优雅的方式转换数据。
Have a look at this post: 看一下这篇文章:
NHibernateUtil.Custom() NHibernateUtil.Custom()
There it is described, that you can use NHibernateUtil.Custom(IUserType) 其中描述了可以使用NHibernateUtil.Custom(IUserType)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.