0

In EF, Order By allows a column name to be used to eg OrderBy("Description")

I need to be able to do some thing similar with GroupBy

Other posts have solutions when the column type is known

var groupByExpressionGN2 = GetGroupByExpressionGuidNull<DebtWaiver>("PersonUID");

...

// in the query 
.GroupBy(groupByExpression2)

// the Expression function
private static Expression<Func<TEntity,Guid?>> GetGroupByExpressionGuidNull<TEntity>(string property)
{
    var item = Expression.Parameter(typeof(TEntity), "gb");
    var itemProperty = Expression.PropertyOrField(item, property);
    var lambda = Expression.Lambda<Func<TEntity, Guid?>>(itemProperty, item);

    return lambda;
}

But my users may select 1 of any columns by which to group by

So how can I make the function above return an expression for group by

I have tried this:

public static Expression<Func<T, object>> GetMember<T>(string memberName)// where T : EntityObject
{
    ParameterExpression pe = Expression.Parameter(typeof(T), "p");
    System.Reflection.PropertyInfo pi = typeof(T).GetProperty(memberName);
    return (Expression<Func<T, object>>)Expression.Lambda<Func<T, object>>(Expression.Convert(Expression.Property(pe, pi), typeof(object)), pe);
}

but it produces : p =>Convert(p.PersonUID)

instead of:p =>p.PersonUID

Regards

GregJF

GregJF
  • 456
  • 4
  • 14

1 Answers1

0

After a bit more testing (and a good night's sleep) I got the second method to work (Thanks to JA Rreyes )

My issue was that I was using this:

var groupByExpressionGN2 = GetGroupByExpressionGuidNull<DebtWaiver>("PersonUID");

...

// in the query 
.GroupBy(groupByExpression2)

I should have being doing this:

var groupByExpression2 = GetMember<DebtWaiver>("PersonUID");

...

// in the query 
.GroupBy(groupByExpression2.Compile())

You can use the second method in my original post( GetMember ), but I use this method('cos I like it!): Thanks: Taher Rahgooy

public static Expression<Func<T, object>> GetPropertySelector<T>(string propertyName)
{
    var arg = Expression.Parameter(typeof(T), "gb");
    var property = Expression.Property(arg, propertyName);
    var conv = Expression.Convert(property, typeof(object));
    var exp = Expression.Lambda<Func<T, object>>(conv, new ParameterExpression[] { arg });
    return exp;
}

Regards

GregJF

Community
  • 1
  • 1
GregJF
  • 456
  • 4
  • 14