在nhibernate中执行自定义查询并映射到自定义域对象

时间:2012-03-07 14:01:36

标签: c# sql nhibernate

您好我有这样的查询

SELECT Customer.Name, sum([Load].Profit) as Profit FROM Customer INNER JOIN [Load] ON Customer.Id = [Load].CustomerId GROUP BY Customer.Name

我需要在nhibernate中执行此查询并将其映射到我创建的自定义域对象

public class CustomerProfit
    {
        public String Name;
        public Decimal Profit;

    }

有可能这样做吗?以及如何,或者是否可以在HQL中执行此自定义查询?

1 个答案:

答案 0 :(得分:14)

public sealed class CustomerProfitQuery : IResultTransformer
{
    public static readonly string Sql = "SELECT Customer.Name, sum([Load].Profit) as Profit FROM Customer INNER JOIN [Load] ON Customer.Id = [Load].CustomerId GROUP BY Customer.Name";
    public static readonly CustomerProfitQuery Transformer = new CustomerProfitQuery();

    // make it singleton
    private CustomerProfitQuery()
    { }

    public IList TransformList(IList collection)
    {
        return collection;
    }

    public object TransformTuple(object[] tuple, string[] aliases)
    {
        return new CustomerProfit
        {
            Name = (string)tuple[0],
            Profit = (decimal)tuple[1],
        };
    }
}


// usage
var customerprofits = session.CreateSQLQuery(CustomerProfitQuery.Sql)
    .SetResultTransformer(CustomerProfitQuery.Transformer)
    .List<CustomerProfit>()