2015-06-19 102 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);