Executing a user request in nhibernate and mapping to a custom domain object

Hi, I have such a request

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 that I created like this.

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

    }

Can this be done? and how, or can this custom query be executed in HQL?

+5
source share
1 answer
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>()
+14
source

All Articles