linq-to-sql结合了子表达式

时间:2010-03-30 22:30:38

标签: linq-to-sql lambda

我需要为子实体创建并组合几个表达式,以便在父项的“任何”运算符上使用它。代码现在看起来像这样:

Expresion<Child, bool> startDateExpression;

if(String.IsNullOrEmpty(startDate)
     startDateExpression = t => true;
else
     startDateExpression = t => t.start_date >= startDate;

Expression<Child, bool> endDateExpression;

if(String.IsNullOrEmpty(endDate)
     endDateExpression = t => true;
else
     endDateExpression = t => t => t.end_date <= endDate;


....
ParameterExpression param = startDateExpression.Parameters[0];

Expression<Func<T, bool>> Combined = Expression.Lambda<Func<Child, bool>>( 
        Expression.AndAlso(startDateExpression.Body, endDateExpression.Body), param);

//but now I am trying to use combined expression on parent 
//this line fails just to give an idea on what I am trying to do:
//filter type is IQueryable<Parent>;
var filter = filter.Where(p =>p.Children.Any(Combined));

我该怎么做?有没有更好的方式(更优雅的方式呢?也许我应该将子表达式转换为父表达式?

1 个答案:

答案 0 :(得分:0)

我不完全确定你为什么要构建表达式而不是使用lambda函数。你试过以下这个吗?

var filter = filter.Where(p =>p.Children.Any(
   child => (String.IsNullOrEmpty(startDate) || child.start_date >= startDate) &&
            (String.IsNullOrEmpty(endDate) || child.end_date <= endDate)
));