Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RavenDB - Optional where clause

Tags:

c#

ravendb

I want to write a RavenDB query that filters by a value if it is available, but if that value is not available, I want it to return all objects. For example, in linq to objects, I can do something like this:

var matches = people.Where(x => x.LastName == userEntry || userEntry == string.Empty).ToList();

But the following will not work:

var matches = RavenSession.Query<Person>().Where(x => x.LastName == userEntry || userEntry == string.Empty).ToList();

Because userEntry is not an indexed value, this throws an exception.

How can I accomplish this?

like image 527
indot_brad Avatar asked Jun 25 '12 18:06

indot_brad


1 Answers

Based on your comment about multiple optional predicates, you should be able to do something like this:

var where = new List<Expression<Func<Person, bool>>>();

if (!string.IsNullOrWhitespace(lastName))
    where.Add(p => p.LastName == lastName);

if (!string.IsNullOrWhitespace(firstName))
    where.Add(p => p.FirstName == firstName);

// etc...

var query = session.Query<Person>();

foreach (var clause in where)
    query = query.Where(clause);

var results = query.ToList();
like image 198
Jim Bolla Avatar answered Oct 20 '22 16:10

Jim Bolla