Check if a String value contains any number by using Lambda Expression Check if a String value contains any number by using Lambda Expression sql sql

Check if a String value contains any number by using Lambda Expression


As far I know you can't apply regular expression in Linq to Entities. What I recommend to do is if you have other conditions call Where method using them first, and then call AsEnumerable to work with Linq to Object which allows you use regular expressions, so you can apply the condition you need:

var query= context.YourDbSet.Where(...)                            .AsEnumerable()                            .Where(m => !Regex.IsMatch(m.EmployeeName, @"\d"));

Or you can also do the following:

var query= context.YourDbSet.Where(...)                            .AsEnumerable()                            .Where(e=>e.!EmployeeName.Any(char.IsDigit));

Update:

A third solution could be using DbSet.SqlQuery method to execute your raw SQL query:

var query= context.YourDbSet.SqlQuery("SELECT * FROM Table WHERE Name NOT LIKE '%[0-9]%'");

Translating that to your scenario would be:

                     // This column names must match with                      //  the property names in your entity, otherwise use *return Json(db.TEmployees.SqlQuery("SELECT EmployeeID,EmployeeName                                     FROM Employees                                     WHERE Status=1 AND Name NOT LIKE '%[0-9]%'"),            JsonRequestBehavior.AllowGet);// Change the value in the first condition for the real int value that represents active employees


You can use Regex.IsMatch.

yourEnumerable.Where(m => !Regex.IsMatch(m.EmployeeName, @"\d"));


EF is limited in its capability to generate the exact SQL you want. I do not know of a specific expression that will generate the pattern [0-9] in your LIKE clause.

The list of String Functions that are supported by EF are documented on MSDN. None of which can be used to determine if a string contains an arbitrary digit or not.

Some other options are:

  • Use the exact SQL you want in C# and call ExecuteStoreCommand
  • Return more objects than you need from the DB and filter in memory using AsEnumerable()

The Equivalent SQL would be something like

SELECT *FROM TEmployeesWHERE Status = {code for active status}  AND Name NOT LIKE '%[0-9]%'