LINQ-To-Entities query with .Where clauses not filtering as expected
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)
开发者_如何学Python .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:
query.Where(...)
to
query = query.Where(...)
Otherwise you're not changing anything, just calling a function without taking the result
Your problem is that you assumed that Enumerable.Where
modifies the existing query. It does not - it returns a new query. You need to assign the result of the call to Where
back to the query
variable:
query = query.Where(p => ... );
you need to modify your code slightly. LINQ doesnt modify the collection, but returns a new value with the result.
query = query.Where(...)
精彩评论