使用表达式树

时间:2015-06-15 15:50:38

标签: linq dynamic group-by multiple-columns

我有以下查询无效

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();

GetExpression就是这个

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);
    }

我想要做的是实施

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

然后在下面的Select中我想使用x.Key.Key1,x.Key.Key2。目前我得到的错误是

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

on NewExpression ne = Expression.New(anonymousType);线。我也不确定GetExpression方法的返回类型,它可能是错误的。

0 个答案:

没有答案