开发者

Using NHibernate to report a table with two sums

开发者 https://www.devze.com 2023-01-27 22:31 出处:网络
I have three tables: People, Purchases, Payments with 1-to-many relationships between People and Purchases, and People and Payments.

I have three tables: People, Purchases, Payments with 1-to-many relationships between People and Purchases, and People and Payments.

I want to generate a report of People showing the sum of their Purchases and Payments.

I can easily generate a report for all people showing the sum of the payments or purchases, vis:

var query = 
  DetachedCriteria.For<People>("People")
  .CreateAlias("Payments", "paymentsMade");

query.SetProjection(Projections.ProjectionList()
  .Add(Projections.GroupProperty("Id"), "Id")
  .Add(Projections.S开发者_StackOverflowum("paymentsMade.Amount"), "TotalPayments")

Can I do this in a single query in NHibernate? Either using the criteria API (preferred) or HQL.


Try something like this:

var query = @"select
                (select sum(pu.Amount) from Purchase pu where pu.People.Id = ppl.Id),
                (select sum(pa.Amount) from Payments pa where pa.People.Id = ppl.Id) 
              from People ppl";

var results = session
                .CreateQuery(query)
                .List();

Or perhaps using ad-hoc mapping:

public class BulkReport
{
    public double Purchases { get; set; }
    public double Payments  { get; set; }
}

var results = session
                .CreateQuery(query)
                .SetResultTransformer(Transformers.AliasToBean(typeof(BulkReport)))
                .List<BulkReport>();

Another option would be using MultiQueries.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号