MethodCallExpression 没有正确设置 orderby

MethodCallExpression is not setting up the orderby correctly

我是这个表情行业的新手。我在这个例子之后建模: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);

您的查询 returns 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) 这完全没用,因为 table 的行没有顺序。我已将其重写为 .OrderBy(x => x.OfficeName)

也许您想在 OrderBy

之后添加一个 .Select(x => x.OfficeName)
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);