NHibernate GroupBy和Sum

我正在开始研究NHibernate,我有一个问题我无法解决,我想知道是否有人可以帮助我。

映射正在“正确”工作但是当我尝试进行分组和求和时,应用程序返回以下错误:

“无法解析属性:Course.Price of:Persistence.POCO.RequestDetail”

var criteria = session.CreateCriteria(typeof(RequestDetail)) .SetProjection( Projections.ProjectionList() .Add(Projections.RowCount(), "RowCount") .Add(Projections.Sum("Course.Price"), "Price") .Add(Projections.GroupProperty("Request"), "RequestId") ) .AddOrder(Order.Asc("RequestId")) .SetResultTransformer(Transformers.AliasToEntityMap) .List(); 

注1:当我接受代码.Add(Projections.Sum ("Course.Price"), "Price") ,应用程序会正确地返回结果。

注2:我唯一能做的就是运行下面的代码:

 query.Length = 0; query.AppendLine("select"); query.AppendLine(" s.Id,"); query.AppendLine(" s.Identification,"); query.AppendLine(" sum(c.Price) as Total"); query.AppendLine("from"); query.AppendLine(" Student s"); query.AppendLine("inner join"); query.AppendLine(" Request r on r.StudentId = s.Id"); query.AppendLine("inner join "); query.AppendLine(" Requestdetail rq on rq.RequestId = r.Id"); query.AppendLine("inner join"); query.AppendLine(" Course c on c.Id = rq.CourseId"); query.AppendLine("Group by"); query.AppendLine(" s.Id, s.Identification"); query.AppendLine("Order by"); query.AppendLine("s.Identification"); IQuery criteria = session.CreateSQLQuery(query.ToString()) .SetResultTransformer(Transformers.AliasToBean()); IList teste = criteria.List(); 

有没有人遇到过这个问题?

我将介绍一些DTO进行结果映射

 public class MyDTO { public virtual int RowCount { get; set; } public virtual decimal Price { get; set; } // type depends on SUM result public virtual int RequestId { get; set; } } 

然后我们只需要添加JOIN(以避免exception消息)

 var criteria = session.CreateCriteria(typeof(RequestDetail)) // the Course.Price comes from some collection // we have to JOIN it .CreateAlias("Course", "Course")// the first is property name, the second is alias .SetProjection( Projections.ProjectionList() .Add(Projections.RowCount(), "RowCount") .Add(Projections.Sum("Course.Price"), "Price") .Add(Projections.GroupProperty("RequestId"), "RequestId") ) .AddOrder(Order.Asc("RequestId")) .SetResultTransformer(Transformers.AliasToBean()) ; var list = criteria.List(); 

猜测JOIN,它可能是不同的实体/属性名称,但本质应该是清楚的。 我们需要这样做。 使用DTO,我们可以轻松地将结果转换为已知类型的列表