2

我需要一些帮助来创建从 dbcontext 获取数据的通用方法并将“orderby”子句作为参数传递。

到目前为止,设法做到了这一点:

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

我需要帮助的部分是如何转换

Expression<Func<T, object>> orderby

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

在运行时。我想避免仅为排序表达式发送额外的类型。

Expression<Func<T, TKey>> orderby

在当前的实现中,字符串参数没有问题

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

但如果我尝试按 int 参数排序

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

抛出异常。这是我想要实现的吗?任何帮助和建议表示赞赏。谢谢

4

1 回答 1

1

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.

于 2014-01-14T16:07:04.363 回答