在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中执行此自定义查询?
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()