Kad
Kad

Reputation: 658

Appending .Where(..) to a Linq.IQueryable

I am building a Linq IQueryable and want to add a different .Where() argument depending on a certain condition. At runtime the appended .Where() doesn't seem to be taken into account. What could be done wrong?

var query = Context.Sessions
   .Where(s => s.UserID.Equals(currentUserID))
   .Where(s => s.ClosedTime.HasValue)
   .Where(s => !s.ApprovedTime.HasValue);

if (type == Models.EnvironmentType.A)
{
   query.Where(s => s.BedroomID.HasValue);
}
else if (type == Models.EnvironmentType.B)
{
   query.Where(s => s.HomeID.HasValue);
}

Thank you!

Upvotes: 1

Views: 2300

Answers (2)

Selman Genç
Selman Genç

Reputation: 101701

You need to assign returning result back to the query.Where creates a new query, it doesn't change the original one.

query = query.Where(s => s.BedroomID.HasValue);

Upvotes: 9

Aaron Palmer
Aaron Palmer

Reputation: 8992

query.Where(s => s.BedroomID.HasValue) is only going to yield a query, it will not alter the existing query.

You need to assign it to the existing query:

query = query.Where(s => s.BedroomID.HasValue);

Upvotes: 1

Related Questions