Reputation: 15579
I am using Predicate Builder to build a dynamic EF predicate.
I want to return all Active users whose firstname or lastname matches the requested search term. Here is what I have tried but but I always get all of the active users... it means the search is not narrowed down by the search term:
string searchTerm = "John"; // <-- comes from user
predicate = predicate.And(u => u.IsActive == true);
if (!string.IsNullOrEmpty(searchTerm))
{
predicate = predicate.Or(u => u.FirstName.Contains(searchTerm));
predicate = predicate.Or(u => u.LastName.Contains(searchTerm));
}
Upvotes: 0
Views: 283
Reputation: 25370
Break down your logic into a simple boolean expression -
x = IsActive == true
y = FirstName match
z = LastName match
Your logic is x or y or z
. If the user is active, they will get returned.
You are wanting x and (y or z)
. Inside your if
statement, something like -
predicate = predicate.And(u => u.FirstName.Contains(searchTerm) || u.LastName.Contains(searchTerm));
Upvotes: 2