NHibernate GroupBy 和 Sum

NHibernate GroupBy and Sum

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

映射正常 "correctly" 但是当我尝试进行分组和求和时,应用程序 returns 出现以下错误:

"could not resolve property: 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") 应用程序时 returns 我的结果是正确的。

注意 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>();

有人遇到过这个问题吗?

我会为结果映射引入一些 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是猜出来的,可能名字不一样entity/property,但本质应该清楚了。我们需要这样做 JOIN。使用 DTO,我们可以轻松地将结果转换为已知类型的列表