MethodCallExpression 未正确设置 orderby



我是这个表达式业务的新手。我正在按照这个例子建模: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);

您的查询返回一个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)

也许您想在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);

相关内容

  • 没有找到相关文章

最新更新