开发者

linq-to-sql combine child expressions

I need to create and combine several expressions for child entity into one to use it on "Any" operator of a parent. Code now looks like this:

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

How can I do that? Is there better(more elegant way way of doing it? Maybe I should convert child expression into parent expression?


I'm not entirely sure why you are building expressions instead of using lambda functions. Have you tried the following?

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜