Map SQL Query to Business object in Nhibernate

南笙酒味 提交于 2020-02-04 14:31:52

问题


I want to map SQL query to Business object using Nhibernate. There are lot fields in Employee table, but I am getting three only and want map only those one.

here is my sql query

<sql-query  name="findEmployeesInfo">
<return alias="emp" class="Calibr.BusinessDocuments.BOs.Employee, BusinessDocuments"/>
<![CDATA[
  select (emp.Eid) as {emp.Id},(emp.FirstName) as {emp.FirstName},(emp.LastName) as {emp.LastName} from Employee emp
 ]]>
</sql-query>

here is I have make constructor to map those columns

public Employee(int Id, string FirstName, string LastName)
{
    this.Id = Id;
    this.FirstName = FirstName;
    this.LastName = LastName;            
}

DB Employee table Column Names: Eid, FirstName,LastName,............

I am getting this exception

could not execute query [ select (emp.Eid) as Eid1_0_,(emp.FirstName) as FirstName1_0_,(emp.LastName) as LastName1_0_ from Employee emp

Edit: if I select all columns, it will work perfect -- Select * from Employee emp

Thanks for your help.


回答1:


I think you would benefit from using NHibernate's ad-hoc mapping features:

Named query:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
    <sql-query name="findEmployeesInfo">
      select emp.Eid as Id, emp.FirstName FirstName, emp.LastName as LastName from Employee emp
    </sql-query>
</hibernate-mapping>

Employee class:

public class Employee
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    // etc...
}

Ad-hoc query:

IList<Employee> employees = session
                              .GetNamedQuery("findEmployeesInfo")
                              .SetResultTransformer(Transformers.AliasToBean(typeof(Employee)))
                              .List<Employee>();


来源:https://stackoverflow.com/questions/5964147/map-sql-query-to-business-object-in-nhibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!