Execute a custom query in nhibernate and map to a custom domain object

北慕城南 提交于 2020-01-03 15:17:08

问题


Hi i have a query like this

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

I need to execute this query in nhibernate and map it to a Custom domain object which i created as like this

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

    }

Is it possible to do so ? and how , or is it possible to execute this custom query in HQL ?


回答1:


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


来源:https://stackoverflow.com/questions/9602878/execute-a-custom-query-in-nhibernate-and-map-to-a-custom-domain-object

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