Question

I need a little help for creating a generic method for fetching data from dbcontext and pass the 'orderby' clause as parameter.

So far a managed to do this:

public virtual Task<List<T>> GetListAsync(Expression<Func<T, object>> orderby, bool asc = true)
{
    IQueryable<T> dbQuery = _dbContext.Set<T>();
    if (orderby != null)
    {
        UnaryExpression UnExp = (UnaryExpression)orderby.Body;
        MemberExpression Exp = (MemberExpression)UnExp.Operand;
        var propInfo = (PropertyInfo)Exp.Member;

        //need new sort expression

        dbQuery = asc ? dbQuery.OrderBy(orderby) : dbQuery.OrderByDescending(orderby);
    }
    return dbQuery.ToListAsync<T>();
}

The part where I need help is how to convert

Expression<Func<T, object>> orderby

to

Expression<Func<T, "propInfo.PropertyType">> sortExpression

at runtime.I want to avoid sending extra type only for the sort expression.

Expression<Func<T, TKey>> orderby

With current implementation there is no problem with string parameter like

 var data = await GetListAsync(it => it.Name);

but if I try to sort by int parameter

var data = await GetListAsync(it => it.Id);

throws exception.Is that what I want achievable? Any help and advices are appreciated. Thanks

Was it helpful?

Solution

After more research I made this solution:

public virtual Task<List<T>> GetListAsync(Func<IQueryable<T>, IOrderedQueryable<T>> orderby)
{
    IQueryable<T> dbQuery = _dbContext.Set<T>();
    if (orderby != null)
    {
        if (orderby != null)
        {
            dbQuery = orderby(dbQuery);
        }
    }
    return dbQuery.ToListAsync<T>();
}

and usage:

var data = await GetListAsync(q => q.OrderBy(it => it.Name))

I hope this help someone.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top