使用Lambda Expression检查String值是否包含任何数字

Jac*_*ack 11 sql linq asp.net-mvc lambda entity-framework

我有一个SQL查询只检索不包含任何数字的名称:

...
WHERE Name NOT LIKE '%[0-9]%'
Run Code Online (Sandbox Code Playgroud)

另一方面,当尝试使用Lambda Expression不同组合使用此查询时,如下所示,它们都不起作用不起作用:

.Where(m => !m.EmployeeName.Contains("%[0-9]%")
Run Code Online (Sandbox Code Playgroud)

要么

 .Where(m => !m.EmployeeName.Contains(".*[0-9].*")
Run Code Online (Sandbox Code Playgroud)

我该如何使用NOT LIKE方法Lambda Expression

更新:我的lambda表达式如下所示:

return Json(db.TEmployees
    .Where(m => m.Status == Enums.Status.Active)
    .AsEnumerable()
    .Where(m => !Regex.IsMatch(m.EmployeeName, ".*[0-9].*"))
    .Select(m => new { ID = m.EmployeeID, EmployeeName = m.EmployeeName }), 
        JsonRequestBehavior.AllowGet);
Run Code Online (Sandbox Code Playgroud)

oct*_*ccl 5

据我所知,你不能在Linq中将正则表达式应用于实体.我建议你做的是如果你有其他条件调用Where方法首先使用它们,然后调用AsEnumerable使用Linq to Object,它允许你使用正则表达式,这样你就可以应用你需要的条件:

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

或者您也可以执行以下操作:

var query= context.YourDbSet.Where(...)
                            .AsEnumerable()
                            .Where(e=>e.!EmployeeName.Any(char.IsDigit));
Run Code Online (Sandbox Code Playgroud)

更新:

第三种解决方案可能是使用DbSet.SqlQuery方法来执行原始SQL查询:

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

将其转换为您的方案将是:

                     // 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
Run Code Online (Sandbox Code Playgroud)