Group by multiple columns using expression trees

383 views Asked by At

I have the following query which does not work

var municipalities = session.Query<Repositorio_Resultado>()
                .Where(x => ...)
                .GroupBy(GetExpression(argument))
                .Select(x => new SelGeo_DTO()
                 { 
                     COORD_LAT = x.Average(y => y.CoordYLat.Value),
                     COORD_LON = x.Average(y => y.CoordXLon.Value)
                })
                .ToList();

where GetExpression is this

private Expression<Func<Repositorio_Resultado, object>> GetExpression(string level2GroupBy)
    {
        ParameterExpression pe = Expression.Parameter(typeof(Repositorio_Resultado), "x");

        Type anonymousType = new { Key1 = "", Key2 = "" }.GetType();
        NewExpression ne = Expression.New(anonymousType);
        MemberInitExpression mie = Expression.MemberInit(ne, new MemberBinding[]
        {
            Expression.Bind(anonymousType.GetMember("Key1")[0], Expression.Constant(level2GroupBy)),
            Expression.Bind(anonymousType.GetMember("Key2")[0], Expression.Constant(string.Format("ID_{0}", level2GroupBy)))
        });

        return Expression.Lambda<Func<Repositorio_Resultado, object>>(mie, pe);
    }

what I want to do is implement

.GroupBy(x => new { x.A, x.B })

and then in the Select that follows I want to use x.Key.Key1, x.Key.Key2. Currently the error I get is

Type '<>f__AnonymousType2`2[System.String,System.String]' does not have a default constructor

on the NewExpression ne = Expression.New(anonymousType); line. I am not sure on the return type of the GetExpression method too, it's probably wrong.

0

There are 0 answers