【问题标题】:Execute a custom query in nhibernate and map to a custom domain object在 nhibernate 中执行自定义查询并映射到自定义域对象
【发布时间】:2012-03-07 14:01:35
【问题描述】:

您好,我有一个这样的查询

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

【问题讨论】:

  • 你更喜欢什么:a) 使用 resulttransformer 做最少的工作,但没有 changetracking b) 映射为具有自定义 sql 的实体和更多工作,但更改跟踪和东西
  • 作为要求,我认为我更喜欢 :-)
  • 看到这个答案stackoverflow.com/questions/5964147/…也许对你有帮助;)

标签: c# sql nhibernate


【解决方案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>()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 2011-12-06
    • 1970-01-01
    • 2017-08-01
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    相关资源
    最近更新 更多