Mimic an OrWhere expression when dynamically building LINQ queries?

The code snippet below the search allows the user to map a row to three fields in a table. If any of the fields matches, the record is included in the result. However, the use of the "Where to filter the results" parameter leads to the fact that "the string must match all three fields" instead of "the string can match any of the three fields."

Is there a way to mimic an OrWhere expression when dynamically building LINQ queries?

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 use the Entities Framework and LINQ to Entities, and I am making an MVC3 web application.

+4
source share
2 answers

Not quite pretty, but it will work.

 var foundUsers = entities.UserInfo.Where(u => (searchCompleteName && u.CompleteName.Contains(searchString)) || (searchPortalID && u.PortalID.Contains(searchString)) || (searchUsername && u.UserIdentity.Contains(searchString)); 

You can also do this with a union. The union operator returns different results, so there will be no duplicates. I have no idea if EF can put this back to the database.

 var foundUsers = Enumerable.Empty<UserInfo>().AsQueryable(); if (searchCompleteName) { foundUsers = foundUsers.Union(entities.UserInfo.Where(u => u.CompleteName.Contains(searchString))); } if (searchPortalID) { foundUsers = foundUsers.Union(entities.UserInfo.Where(u => u.PortalID.Contains(searchString))); } if (searchUsername) { foundUsers = foundUsers.Union(entities.UserInfo.Where(u => u.PortalID.Contains(searchString))); } 
+2
source

Source: https://habr.com/ru/post/1345190/


All Articles