NHibernate GroupBy and Sum

本文关键字:Sum and GroupBy NHibernate | 更新日期: 2023-09-27 18:11:53

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

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

"无法解析属性:航向。"价格: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<Teste>());
IList<Teste> teste = criteria.List<Teste>();

有人遇到过这个问题吗?

NHibernate GroupBy and Sum

我将为结果映射引入一些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(以避免异常消息)

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<MyDTO>())
    ;
var list = criteria.List<MyDTO>();

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