2015-06-19 97 views
0

我对这个表达式业务很陌生。我在此示例之后建模:https://msdn.microsoft.com/en-us/library/vstudio/bb882637(v=vs.110).aspxMethodCallExpression没有正确设置订单

我试图获得满足特定名称的办公室列表。代码工作到我需要通过设置顺序。我不断收到此错误:

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

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

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

后添加.Select(x => x.OfficeName)那就真的是:

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