MethodCallExpression未正确设置orderby

时间:2015-06-19 20:48:34

标签: c# linq expression

我是这个表达业务的新手。我在这个例子之后进行建模:https://msdn.microsoft.com/en-us/library/vstudio/bb882637(v=vs.110).aspx

我正在尝试获取满足特定名称的办公室列表。代码可以解决我需要设置顺序的问题。我一直收到这个错误:

ParameterExpression of type 'DB.Office' cannot be used for delegate parameter of type 'System.String'

这是代码

        IQueryable<Office> offices = GetAllOffices();
        ParameterExpression pe = Expression.Parameter(typeof(Office), "Office");
        Expression left = Expression.Property(pe, typeof(Office).GetProperty("OfficeName"));
        Expression right = Expression.Constant(filterRequest.Filters.Value);
        Expression e1 = Expression.Equal(left, right);

        Expression predicateBody = e1;

        MethodCallExpression whereCallExpression = Expression.Call(
            typeof(Queryable),
            "Where",
            new Type[] { offices.ElementType },
            offices.Expression,
            Expression.Lambda<Func<Office, bool>>(predicateBody, new ParameterExpression[] { pe }));

        MethodCallExpression orderByCallExpression = Expression.Call(
            typeof(Queryable),
            "OrderBy",
            new Type[] { offices.ElementType, offices.ElementType },
            whereCallExpression,
            Expression.Lambda<Func<string, string>>(pe, new ParameterExpression[] { pe }));

        IQueryable<string> results = offices.Provider.CreateQuery<string>(orderByCallExpression);

1 个答案:

答案 0 :(得分:1)

您的查询返回Office,因此您应该

IQueryable<Office> results = offices.Provider.CreateQuery<Office>(orderByCallExpression);

请注意,您的OrderBy错误了...

应该是这样的:

MethodCallExpression orderByCallExpression = Expression.Call(
    typeof(Queryable),
    "OrderBy",
    new Type[] { offices.ElementType, typeof(string) },
    whereCallExpression,
    Expression.Lambda<Func<Office, string>>(left, new ParameterExpression[] { pe }));

如果您想按OfficeName订购。你写的是:.OrderBy(x => x)这是没用的,因为表的行没有排序。我已将其重写为.OrderBy(x => x.OfficeName)

也许您想在.Select(x => x.OfficeName)

之后添加OrderBy
MethodCallExpression selectCallExpression = Expression.Call(
    typeof(Queryable),
    "Select",
    new Type[] { offices.ElementType, typeof(string) },
    orderByCallExpression,
    Expression.Lambda<Func<Office, string>>(left, new ParameterExpression[] { pe }));

那真的是:

IQueryable<string> results = offices.Provider.CreateQuery<string>(selectCallExpression);
相关问题