Searching Using Expression Trees

5 views
Skip to first unread message

Sam-I-Am

unread,
Feb 14, 2010, 4:22:52 AM2/14/10
to ncommon
I have added the following method to my instance of RepositoryBase:
public IQueryable<TEntity> Search(IList<Expression<Func<TEntity,
bool>>> criteria)
{
var query = RepositoryQuery;
foreach (var criterion in criteria)
{
query = query.Where(criterion);
}
return query.AsQueryable();
}

This lets me build up expressions to be passed in for searching:
[Test]
public void Can_Use_QueryHandler()
{
QueryHandler<Event> queryHandler = new
QueryHandler<Event>();
queryHandler.AddCriteria(x =>
x.Venue.Address.Region.Name.Equals("Western Cape"));
queryHandler.AddCriteria(x => x.Name.Contains("Test"));
queryHandler.AddCriteria(x => x.EventStatus ==
EventStatus.Live);

IList<Event> results;
using (UnitOfWorkScope scope = new UnitOfWorkScope())
{
results =
_eventRepository.Search(queryHandler.Criteria).ToList();
}

}

public class QueryHandler<T> where T : IEntity
{
private IList<Expression<Func<T, bool>>> _criteria;

public QueryHandler(){

_criteria = new List<Expression<Func<T, bool>>>();
}

/// <summary>
///
/// </summary>
/// <param name="func">A lambda function to apply</param>
public void AddCriteria(Expression<Func<T, bool>> func)
{
_criteria.Add(func);
}

public IList<Expression<Func<T, bool>>> Criteria
{
get
{
return _criteria;
}
}
}

Ritesh Rao

unread,
Apr 5, 2010, 5:52:34 PM4/5/10
to ncommon
I'm not sure how this is any more useful than specifying predicates as
linq expressions using where? If the intent is to re-use predicates, I
would classify those as specifications, and you can specify
specifications using the Specification base class (you can even
combine multiple specifications which effectively do the exact same
thing as below).
Reply all
Reply to author
Forward
0 new messages