开发者

Map SQL Query to Business object in Nhibernate

开发者 https://www.devze.com 2023-03-04 21:58 出处:网络
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.

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 Employe开发者_JS百科e 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.


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>();
0

精彩评论

暂无评论...
验证码 换一张
取 消