Search code examples
devforce

DevForce 2012 Punch Cocktail Repository Query with Selector to Search for Max Result


I am Trying to Query a Table for a Max Value (long) with some parameters, trying to use the Punch Framework.

Here is the original LINQ Query:

Table.Where(x=>x.GroupId == 1).Max(x=>x.LongValue)

I am Tying to convert this LINQ Query to use the Cocktail Repository:

(await UnitOfWork.GetRepository<Table>()
            .FindAsync(selector => selector.Select(x => x.LongValue), predicate => predicate.GroupId.Equals(1),))
            .FirstOrDefault();

This works fint to select the first LongValue of the Group, but how can i change the Query to give me the Max result of the Table?


Solution

  • DevForce proper uses the AsScalarAsync method to handle async execution of scalar queries. Punch doesn't directly implement this, but you can extend your repository class to provide this. It will look similar to how the base Repository<T> class implements CountAsync. Something like this:

    public Task<long> MaxAsync(Expression<Func<T, bool>> predicate, 
           Expression<Func<T, long>> projection) 
    {
        return this.GetFindQuery(predicate, null, null).AsScalarAsync().Max(projection);
    }
    

    DevForce has several overloads for Max, so check the docs to see which works best for you.