如何让 NHibernate 映射到元组或类? [英] How can I get NHibernate to map to a Tuple or Class?
问题描述
我有以下方法可以从数据库中获取结果列表.
I have the following method to get a list of results from the database.
public static IList<T> Find<T>(DetachedCriteria crit) where T : class
{
lock (_locker)
{
return crit.GetExecutableCriteria(InstanceSession)
.List<T>();
}
}
这通常效果很好.但是,我已经更改了一个调用上述方法的方法.
This generally works well. However, I've changed a method that calls the method above from.
public IList<FooBarResult> FindResults(FooBarTask st)
{
return DataAccess.Find<FooBarResult>(DetachedCriteria.For<FooBarResult>()
.Add(Restrictions.Eq("Task", st))).ToList();
}
哪个有效(因为我不想返回整个 FooBarResult
,只返回其中的某些列).
Which works, to this (as I don't want to return the whole of FooBarResult
, just certain columns on it).
public IList<Tuple<DateTime, Guid>> FindResults(FooBarTask st)
{
return DataAccess.Find<Tuple<DateTime, Guid>>(DetachedCriteria.For<FooBarResult>()
.Add(Restrictions.Eq("Task", st))
.SetProjection(
Projections.ProjectionList()
.Add(
Projections.Property("FieldOne")
)
.Add(
Projections.Property("FieldTwo")
)
)
)
.ToList();
}
我希望顶部的 Find
方法会自动将列表的条目转换为 Tuple
,但它只返回 System.Object[]代码>.
I was hoping that the Find
method at the top would automatically cast the entries of the list to Tuple
, but it just returns System.Object[]
.
有什么办法可以让它返回一个元组列表?
Is there any way I can make it return a list of tuples?
推荐答案
您可以尝试使用 SetResultTransformer
,如 这个答案:
You can try using SetResultTransformer
as explained in this answer:
var tupleConstructor = typeof(Tuple<DateTime, Guid>).GetConstructors()[0];
然后:
return DataAccess.Find<Tuple<DateTime, Guid>>(DetachedCriteria.For<FooBarResult>()
.Add(Restrictions.Eq("Task", st))
.SetProjection(
Projections.ProjectionList()
.Add(
Projections.Property("FieldOne")
)
.Add(
Projections.Property("FieldTwo")
)
).SetResultTransformer(Transformers.AliasToBeanConstructor(tupleConstructor))
).ToList();
这篇关于如何让 NHibernate 映射到元组或类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!