7

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 ?

3
  • 2
    what do you prefer: a) minimal work with resulttransformer but no changetracking b) mapping as entity with custom sql and more work but change tracking and stuff Commented Mar 7, 2012 at 15:18
  • 1
    As the requirement i think i prefer a :-) Commented Mar 7, 2012 at 15:58
  • See this answer stackoverflow.com/questions/5964147/… Maybe helpful to you ;) Commented Dec 4, 2013 at 4:26

1 Answer 1

17
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>()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.