本文介绍了将 Nhibernate 查询转换为通用列表时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 EmployeeEntity 的简单实体,其属性为 IDNameAgeOrganisation指定.我只是使用查询

I have a simple entity called EmployeeEntity with properties ID, Name, Age, Organisation, and Designation. I am just querying the database using the query

IQuery query = session.CreateQuery(
    "select Name, Designation, Age, Organisation FROM EmployeeEntity " +
    "group by Name, Designation, Age, Organisation");

IList<EmployeeEntity> employee = query.List<EmployeeEntity>(); // Throws error

但是在转换为我的类型时,它会引发异常:

but on conversion to my type, it's throwing an exception:

无法执行查询[SQL: SQL not available]

带有 InnerException:

值System.Object[]"不是NHibernateTest.EmployeeEntity"类型,不能在这个泛型集合中使用.
参数名称:值

虽然使用此查询可以正常工作:

though it works fine using this query:

IQuery query = session.CreateQuery("select e FROM EmployeeEntity e group by e");

IList<EmployeeEntity> employee = query.List<EmployeeEntity>();

但我不想选择所有列,因为我不需要它们.

but I don't want to select all the columns because I don't need them.

推荐答案

如果您只需要一组特定的列,请创建一个与您的列一对一映射的类.像这样:

If you only want a certain set of columns, create a class that maps one to one with your columns. Like so:

public class EmployeeView
{
    public string Name { get; set; }
    public string Designation { get; set; }
    public int Age { get; set; }
    public string Organization { get; set; }
}

然后你只需要在你的查询中添加一个结果转换器

You then just need to add a result transformer to your query

IQuery query = session
    .CreateQuery("select Name ,Designation ,Age ,Organisation  FROM EmployeeEntity   group by  Name ,Designation ,Age ,Organisation")
    .SetResultTransformer(Transformers.AliasToBean<EmployeeView>());

Ilist<EmployeeEntity> employee= query.List<EmployeeView>();

这篇关于将 Nhibernate 查询转换为通用列表时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-20 23:53