The code snippet below search allow the user to match a string against three fields in the table. If any of the fields match, the entry is included in the result. However, using Where to filter out the results is resulting in "the string must match all three fields" instead "the string can match any of the three fields".
Is there a way to simulate an OrWhere expression when building LINQ queries dynamically?
var foundUsers = from UserInfo user in entities.UserInfo
select user;
if (searchCompleteName)
{
foundUsers = foundUsers.Where(u => u.CompleteName.Contains(searchString));
}
if (searchPortalID)
{
foundUsers = foundUsers.Where(u => u.PortalID.Contains(searchString));
}
if (searchUsername)
{
foundUsers = foundUsers.Where(u => u.UserIdentity.Contains(searchString));
}
PS. I am using Entities Framework and LINQ to Entities, and am doing a MVC3 Web Application.
Try this:- http://www.albahari.com/nutshell/predicatebuilder.aspx
Not exactly pretty, but it would work.
You could also do this with a union. The union operator returns distinct results so there will not be any duplicates. I have no idea if EF can defer this to the database.