lundi 22 janvier 2018

Error Group by string column name (run time column name)

I am encountering errro in q.GroupBy method in below code It Says :

     Cannot implicitly convert type 
     'System.Linq.IQueryableg<System.Linq.IGrouping<TRet, TModel>>' to 
     'System.Linq.IQueryable<TModel>

Above is error thrown

    public static IQueryable<TModel> GroupByDynamic<TModel>(this IQueryable<TModel> q, string name)
    {
        Type entityType = typeof(TModel);
        PropertyInfo p = entityType.GetProperty(name);
        MethodInfo m = typeof(QueryableHelper).GetMethod("GroupByProperty").MakeGenericMethod(entityType, p.PropertyType);          
        return (IQueryable<TModel>)m.Invoke(null, new object[] { q, p });
    }


    public static IQueryable<TModel> GroupByProperty<TModel, TRet>(IQueryable<TModel> q, PropertyInfo p)  
    {
        ParameterExpression pe = Expression.Parameter(typeof(TModel));
        Expression se = Expression.Convert(Expression.Property(pe, p), typeof(TRet));
        return q.GroupBy(Expression.Lambda<Func<TModel, TRet>>(se, pe));
    }

Belwo code q.OrderBy Working without any issue

   public static IQueryable<TModel> OrderByProperty<TModel, TRet>(IQueryable<TModel> q, PropertyInfo p)
    {
        ParameterExpression pe = Expression.Parameter(typeof(TModel));
        Expression se = Expression.Convert(Expression.Property(pe, p), typeof(TRet));
        return q.OrderBy(Expression.Lambda<Func<TModel, TRet>>(se, pe));
    }





Aucun commentaire:

Enregistrer un commentaire