Aggregation with NHibernate.FlowQuery

Aggregation is quite easy in NHibernate.FlowQuery (FlowQuery) but in can be a bit unclear how to do it. This post is supposed to make it a bit clearer by giving a couple of examples.

With FlowQuery all aggregation is done by using the Aggregate-helper, like:

session.FlowQuery<User>()
    .Select(x => new
    {
        Average = Aggregate.Average(x.Id),
        Max = Aggregate.Max(x.Id),
        Min = Aggregate.Min(x.Id)
    });

This will return a FlowQuerySelection<Anonymous> containing one item that holds the selected aggregations.

Quite easy, right?

To group by a certain property, you also have to select that certain property in a GroupBy-aggregation, like:

session.FlowQuery<User>()
    .Select(x => new
    {
        Average = Aggregate.Average(x.Id),
        Max = Aggregate.Max(x.Id),
        Min = Aggregate.Min(x.Id),
        GroupedBy = Aggregate.GroupBy(x.Firstname)
    });

Now the aggregation will be grouped by Firstname and the returned FlowQuerySelection<Anonymous> will no longer contain only one item but instead one item for each unique Firstname in the database table.

Enjoy! (:

/Niklas Källander

Advertisements