Searching for text in a database with Entity Framework Searching for text in a database with Entity Framework oracle oracle

Searching for text in a database with Entity Framework


Just add the predicates conditionally:

var users = from u in context.TPM_USER select u;if (!string.IsNullOrWhiteSpace(FirstName))    users = users.Where(u => u.FIRSTNAME.ToLower().Contains(FirstName.ToLower()));if (!string.IsNullOrWhiteSpace(LastName))    users = users.Where(u => u.LASTNAME.ToLower().Contains(LastName.ToLower()));

Or only the LASTNAME predicate as conditional one.

Later addition:

An expression like Where(u => u.FIRSTNAME.ToLower()... is better to be avoided. They cause any indexes on FIRSTNAME to be ignored, because the field value is converted first and then compared (see here for more details).

There's a big chance you don't need these lower-case conversions. Check the database collation of the field. If it's case-insensitive (CI), which it probably is, you don't need these conversions.


Are you sure that FirstName and LastName aren't null?

You might try writing it like this instead...

string LowerFirstName = (FirstName + "").ToLower();string LowerLastName = (LastName + "").ToLower();var users = (from u in context.TPM_USER             where (LowerLastName == "" || u.LASTNAME.ToLower().Contains(LowerLastName))             && (LowerFirstName == "" || u.FIRSTNAME.ToLower().Contains(LowerFirstName))             select u);


FYI, if anyone runs into this issue with Oracle, here's a workaround:

var users = (from u in context.TPM_USER             where (LastName == null|| u.LASTNAME.ToLower().Contains(LastName.ToLower()))             && (FirstName == null || u.FIRSTNAME.ToLower().Contains(FirstName.ToLower()))             select u);

This will get converted to:

'' is null

In SQL, which Oracle interprets as true.