NHibernate:如何在SelectList中返回根类型对象

时间:2014-04-10 07:20:04

标签: nhibernate nhibernate-projections

我的DTO:

public class ServiceWithCount
{
  public Service Service { get; set; }
  public long Count { get; set; }
}

public class Service
{
  public virtual long Id { get; set; }
  ...
}
public class Vote
{
  public virtual long Id { get; set; }
  public virtual Service Service { get; set; }
  ...
}

我想做点什么:

ServiceWithCount dto = null;
Service serviceAlias = null;

var result = session.QueryOver<Service>(() => serviceAlias)
  .Where(x => x.Serie.Id == serie.Id)
  .SelectList(list =>
    list
      .SelectSubQuery(QueryOver.Of<Vote>().Where(y => y.Service.Id == serviceAlias.Id).ToRowCountInt64Query()).WithAlias(() => dto.Count)
      .Select(x => x).WithAlias(() => dto.Service) //This line causes error
  )
  .TransformUsing(Transformers.AliasToBean<ServiceWithCount>())
  .List<ServiceWithCount>();

但这会导致错误:

could not resolve property:  of: MyNamespace.Service

如何将根类型对象作为dto的组件返回?

1 个答案:

答案 0 :(得分:0)

使用Linq的解决方案:

添加命名空间:

using System.Linq;
using NHibernate;
using NHibernate.Linq;

并查询类似的内容:

var result = (from s in session.Query<Service>()
             where s.Serie.Id == serie.Id
             let count = session.Query<Vote>().Count(v => v.Service.Id == s.Id)
             select new ServiceWithCount() { Service = s, Count = count })
             .ToList();

我认为在DTO中公开您的实体Service并不是一个好的实践,您可以公开简单的属性只是为了获取您想要传输的信息,避免在DTO内从nhibernate获取代理的风险。