为什么我的LINQ表达式在LINQ to SQL中不起作用?

时间:2010-09-20 16:47:48

标签: c# .net linq-to-sql lambda

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;
}

这是生成我的表达式的函数。

当我这样做时:

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

它告诉我参数'w'不在范围内。

所以问题是,我如何生成我的表达式,这取决于我需要的东西,并将其粘贴到LINQ to SQL查询中?

2 个答案:

答案 0 :(得分: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));
}

这个功能非常有用。它结合了两个表达式并构建了正确的树。

答案 1 :(得分:0)

可能是您尝试返回Expression.Lambda<T>然后将其分配给其层次结构中的SON的对象(System.Linq.Expressions.Expression<T>

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

希望有所帮助,