将类属性传递给方法C#

时间:2014-07-25 18:03:16

标签: c# asp.net iqueryable

我正在尝试创建一个排序方法,该方法将类属性传递给sort。我正在使用ASP .NET和MVC,所以我所指的类实际上是一个模型。问题是我不断收到错误消息:

"Unable to create a constant value of type 'System.Func`2'. Only primitive types or enumeration types are supported in this context."}

这是我的方法:

    public IQueryable<AP_Tasks> GetOrderedList(IQueryable<AP_Tasks> tasks, Func<AP_Tasks, IComparable> prop, string previousSort, string currentSort, int currentCount)
    {
        if (previousSort == null)
        {
            tasks = tasks.OrderBy(x => x.TaskDate);
            return tasks;
        }
        if (previousSort == currentSort)
        {
            if (currentCount % 2 == 0)
                tasks = tasks.OrderByDescending(x => prop);
            else
            {
                tasks = tasks.OrderBy(x => x.TaskDate);
            }
        }
        return tasks;
    }

这是我的电话:

            case "TaskID":
                query = GetOrderedList(query, x => x.TaskID, previousOrder, sortOrder, currentCount);
                break;
            case "TaskDate":
                query = query.OrderByDescending(t => t.TaskDate);
                break;

TaskID是我的新电话。如果案例是TaskDate它会起作用但是因为在很多情况下我想有一个方法来帮我减少冗余。

更新代码

    public IQueryable<AP_Tasks> GetOrderedList(IQueryable<AP_Tasks> tasks, Func<AP_Tasks, IComparable> prop, string previousSort, string currentSort, int currentCount)
    {

        if (previousSort == null)
        {
            tasks = tasks.OrderBy(x => x.TaskDate);
            return tasks;
        }
        if (previousSort == currentSort)
        {
            if (currentCount % 2 == 0)
                tasks = tasks.OrderByDescending(prop);
            else
            {
                tasks = tasks.OrderBy(prop);
            }
        }
        return tasks;
    }

1 个答案:

答案 0 :(得分:2)

您可以使用以下两种方法根据字符串属性名称而不是lambda来命令属性:

public static IQueryable<T> OrderByProperty<T>(this IQueryable<T> query,
    string propertyName)
{
    var parameter = Expression.Parameter(typeof(T));
    var selector = Expression.Lambda(Expression.Property(parameter, propertyName),
        parameter);
    return Queryable.OrderBy(query, (dynamic)selector);
}
public static IQueryable<T> OrderByDescendingProperty<T>(this IQueryable<T> query,
    string propertyName)
{
    var parameter = Expression.Parameter(typeof(T));
    var selector = Expression.Lambda(Expression.Property(parameter, propertyName),
        parameter);
    return Queryable.OrderByDescending(query, (dynamic)selector);
}

这使您可以简单地将您已经切换的任何字符串传递给方法和顺序,而无需在编译时单独覆盖每个案例。