0

I have a question regarding a Linq to SQL query.

I have following situation:

I have a search with lots of options, like location, availability, name, language etc ...

For this options i have to execute a query to retrieve the results according to options selected, how can i best do it, i cannot write a linq query like for each possibility and combination of options, but i cannot write one for all of them as it will not work, for example:

from p in context.people where p.location==model.location && p.availability==model.availability .... select p

In this case imagine availability is not selected and should not be searched for, but in this case it will be passed as false, or if location is not set and is null so it will only search for empty locations, although i just need all.

So my question is how do people handle this kind of behaviour with queries?

3 Answers 3

2

As you long as you do not execute the linq query immediately you can just add where clauses to it. You can do this for example:

var query = from p in context.people;
if(searchOnLocation)
{
    query = query.where(p => p.location == model.location);
}
if(otherSearch)
{
    query = query.where(p => p.someOtherProperty == someotherValue);
}

var result = query.ToList();

As long you don't call ToList() on your IQueryable, the linq will not be translated into SQL. It's only in the last call, that the linq will be translated and executed against the database

Sign up to request clarification or add additional context in comments.

Comments

1
IQueryable<Person> query = context.people;
if(model.location != null)
    query = query.Where(x => x.location == model.location);
if(model.availability != null)
    query = query.Where(x => x.availability == model.availability);
// etc

Basically, you can compose more and more restrictions as you go.

Comments

0

If you want to implement query without if condition than you can use following syntax:

 var query = context.people.
                where(p => p.location == (model.location ?? p.location) 
                          && p.availability == (model.availability ?? p.availability))
               .ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.