2010-09-20 62 views
1
private System.Linq.Expressions.Expression<Func<ActionLogs, bool>> GetExpression() 
{ 
    Expression<Func<ActionLogs, bool>> expr = w => w.ID != -1; 
    if (ActionDate != null) 
    { 
     Expression<Func<ActionLogs, bool>> byDate = w => w.DateAction == ActionDate; 
     var body = Expression.AndAlso(expr.Body, byDate.Body); 
     expr = Expression.Lambda<Func<ActionLogs, bool>>(body, expr.Parameters[0]); 
    } 

    if (ActionType != ActionTypeEnum.Empty) 
    { 
     Expression<Func<ActionLogs, bool>> byActionType = w => w.ActionTypeID == (int)ActionType; 
     var body = Expression.AndAlso(expr.Body, byActionType.Body); 
     expr = Expression.Lambda<Func<ActionLogs, bool>>(body, expr.Parameters[0]); 
    } 

    if (!String.IsNullOrWhiteSpace(AuthorLogin)) 
    { 
     Expression<Func<ActionLogs, bool>> byLogin = w => w.User.LoginName == AuthorLogin; 
     var body = Expression.AndAlso(expr.Body, byLogin.Body); 
     expr = Expression.Lambda<Func<ActionLogs, bool>>(body, expr.Parameters[0]);    
    } 

    if (!String.IsNullOrWhiteSpace(AdditionalInfo)) 
    { 
     Expression<Func<ActionLogs, bool>> byAdditionalInfo = w => w.DescriptionText.Contains(AdditionalInfo); 
     var body = Expression.AndAlso(expr.Body, byAdditionalInfo.Body); 
     expr = Expression.Lambda<Func<ActionLogs, bool>>(body, expr.Parameters[0]); 
    } 

    return expr; 
} 

這是生成我的表達式的函數。爲什麼我的LINQ表達式在LINQ to SQL中不起作用?

,當我做到這一點:

System.Linq.Expressions.Expression<Func<ActionLogs, bool>> expr = GetExpression(); 
result = blablabla.Where(expr); 

這對我說,「W」的參數不在範圍內。

所以問題是,我如何生成我的表達式,這取決於我需要的東西,並將其粘貼到LINQ to SQL查詢中?

+1

它會在哪一行發生錯誤?我需要知道在上面的例子中是從哪裏拋出的錯誤,而不是「行364」 – 2010-09-20 16:51:24

+0

here:result = blablabla.where(expr); – Dmitry 2010-09-20 17:52:32

回答

1
public Expression<Func<T, bool>> Combine<T>(Expression<Func<T, Boolean>> first, Expression<Func<T, Boolean>> second) 
{ 
    var toInvoke = Expression.Invoke(second, first.Parameters.Cast<Expression>()); 
    return (Expression.Lambda<Func<T, Boolean>>(Expression.AndAlso(first.Body, toInvoke), first.Parameters)); 
} 

此功能是非常有幫助的。它結合了兩個表達式並構建了正確的樹。

+0

)不要忘記接受你自己的答案是正確的 – abatishchev 2010-09-21 06:02:20

0

難道你試圖返回Expression.Lambda<T>,然後將其分配給一個對象,它是它的一個兒子在其層次結構(System.Linq.Expressions.Expression<T>

請看看http://msdn.microsoft.com/en-us/library/system.linq.expressions.lambdaexpression.aspx

。希望幫助,

+0

但是當我這樣做:Expression > expr = w => w.ID!= -1; result = blablabla.where(expr);有用。我嘗試着在調試時加入這兩個expr,並發現不同類型的主體。但我無法找到這種情況的解決方案( – Dmitry 2010-09-20 17:51:10

相關問題