NHibernate:如何在Session.QueryOver中使用ExpandoResultTransformer

时间:2013-09-10 18:44:51

标签: nhibernate queryover

我创建了一个ExpandoResultTransformer,用于将查询结果转换为dto以在UI中使用。它看起来像这样:

  public class ExpandoResultTransformer : IResultTransformer
    {
        public object TransformTuple(object[] tuple, string[] aliases)
        {
            dynamic toReturn = new ExpandoObject();
            for (int i = 0; i < aliases.Length; i++)
            {
                ((IDictionary<string, object>)toReturn)[aliases[i]] = tuple[i];
            }
            return toReturn;
        }

        public IList TransformList(IList collection)
        {
            return collection;
        }
    }

当我对createSQLQuery使用它时,它完美地运行

var contacts = _session.CreateSQLQuery("exec up_ClientContactsView @ClientId=:clientId")
                                   .SetParameter("clientId", request.ClientId)
                                   .SetResultTransformer(new ExpandoResultTransformer())
                                   .List<dynamic>();

但是,当我尝试对QueryOver使用它时,我遇到了麻烦。没有发送别名。所以我尝试像这样指定它们

var periodTables = _session.QueryOver<PeriodTable>()
                           .Where(x => x.ClientPolicy.Id == request.ClientPolicyId)
                           .SelectList(list => list
                              .Select(i =>i.Id).WithAlias(()=>info.PeriodTableId) !! does not work as dynamic cannot be used in expression error
                               .Select(i => i.Id).WithAlias(()=>"PeriodTableId" !!! does not work either as it cannot find member error
                           .TransformUsing(new ExpandoResultTransformer())
                           .List<dynamic>();

如何传递别名?

1 个答案:

答案 0 :(得分:6)

您可以使用匿名类型实例充当模板对象:

var template = new { PeriodTableId = 0 };

var periodTables = _session.QueryOver<PeriodTable>()
                       .Where(x => x.ClientPolicy.Id == request.ClientPolicyId)
                       .SelectList(list => list
                          .Select(i =>i.Id).WithAlias(()=>template.PeriodTableId) 
                          )
                       .TransformUsing(new ExpandoResultTransformer())
                       .List<dynamic>();