Predicate on parent using aggregate of child entity

Posts   
 
    
scout
User
Posts: 15
Joined: 14-Dec-2007
# Posted on: 17-May-2011 23:43:34   

I'm using .Net framework 2.0 and v2.6 of LLBLGen.

I have a Bill table in a one-to-many relation with LineItem table, and I'm attempting to retrieve EntityCollection<BillEntity> where the sum of the related LineItem.Amount exceeds 100.

The sql would be select * from Bill where (select sum(Amount) from LineItem where Bill.BillId = LineItem.BillId) > 100

Here's what I have (not working, of course)


    RelationPredicateBucket bucket = new RelationPredicateBucket();
    bucket.Relations.Add(BillEntity.Relations.LineItemEntityUsingBillId);
    bucket.PredicateExpression.Add(new PredicateExpression(LineItemFields.Amount.SetAggregateFunction(AggregateFunction.Sum) > 100));

Any guidance on this is greatly appreciated.

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 18-May-2011 00:21:21   

For that you can use Scalar query expressions:

IRelationCollection rels = new RelationCollection(
     BillEntity.Relations.LineItemEntityUsingBillId);

EntityField2 fieldToFilter = new EntityField2("TotalAmount", 
     new ScalarQueryExpression(
          new EntityField2("TotalAmount",  LineItemFields.Amount, AggregateFunction.Sum),
          null, soldRelations ));

RelationPredicateBucket bucket = new RelationPredicateBucket();   
bucket.PredicateExpression.Add(fieldToFilter > 100));
David Elizondo | LLBLGen Support Team