I’m making a project for my studies. During construction of the search engine for my application, I’ve ended with code like this:
public List<Document> FindDocument(string docName, Company company,
Department departament, Worker worker,
DateTime? enterDate, DateTime? expDate,
State state)
{
IQueryable<Document> query = context.Documents
.Include(p => p.Department)
.Include(p => p.Company)
.Include(p => p.State)
.Include(p => p.Workers);
if (docName != null)
query.Where(p => p.DocumentName.Contains(docName));
if (company != null)
query.Where(p => p.Company.Equals(company));
if (departament != null)
query.Where(p => p.Department.Equals(departament));
if (worker != null)
query.Where(p => p.Workers.Contains(worker));
if (enterDate.HasValue)
query.Where(p => p.EnterDate.Equals(enterDate.Value));
if (expDate.HasValue)
query.Where(p => p.ExpDate.Equals(expDate.Value));
if (state != null)
query.Where(p => p.State.Equals(state));
return query.ToList();
}
Searching criteria are optional so I need to check if any of the criteria are nulls. The application is made so that if this criterion is not used then its value is null.
The problem with this query is that it always returns all the documents, and not only documents satisfying the criteria. I checked with the debugger at run-time to ensure that if a value is specified then the if statement body is evaluated.
You need to change the statements:
to
Otherwise you’re not changing anything, just calling a function without taking the result