2014-04-23 24 views
1

我嘗試concate兩個表達式,但得到的錯誤提稱號編譯方法:Expression.Or - 變量「A」型的「約會」的範圍「」引用,但它沒有定義

Expression<Func<Appointment, bool>> week1 = StartDateIsBetween(lastMonday, nextSunday); 
Expression<Func<Appointment, bool>> week2 = EndDateIsBetween(lastMonday, nextSunday); 
BinaryExpression weekOr = Expression.Or(week1.Body, week2.Body); 

Func<Appointment, bool> week = Expression.Lambda<Func<Appointment, bool>>(weekOr, week1.Parameters.Single()).Compile(); 

另外兩種方法來創建表達式:

private Expression<Func<Appointment, bool>> StartDateIsBetween(DateTime beginningDate, DateTime endDate) 
    { 
     return a => a.StartDate >= beginningDate && a.StartDate <= endDate; 
    } 

    private Expression<Func<Appointment, bool>> EndDateIsBetween(DateTime beginningDate, DateTime endDate) 
    { 
     return a => a.EndDate >= beginningDate && a.EndDate <= endDate; 
    } 

任何想法如何解決這個錯誤?我是表達樹的初學者:/

+0

你確定你真的需要一個表達式樹? –

回答

3

week1week2有不同的參數,因爲它們是分開創建的。最簡單的方法是使用您現有的表情ExpressionInvoke,新ExpressionParameter實例:

var param = Expression.Parameter(typeof(Appointment)); 
var weekOr = Expression.Or(Expression.Invoke(week1, param), Expression.Invoke(week2, param)); 

var week = Expression.Lambda<Func<Appointment, bool>>(weekOr, param).Compile(); 
+0

非常感謝!我對這個表達式以及它的工作方式感到困惑:/ – netmajor

相關問題