以下代码失败,错误:
LINQ to Entities does not recognize the method 'Boolean CompareNames(System.String, System.String)' method, and this method cannot be translated into a store expression.
我知道我的CompareNames
方法无法转换为SQL语句,但想要知道一种方法来完成此任务,而无需从数据库中提取整个表进行比较。
// Use my method in Linq to Sql lambda
Repo.Get<T>(c => CompareNames(c.Name, newName)).ToList()
// Compare two names removing spaces and non-numeric characters
private static bool CompareNames(string str1, string str2)
{
str1 = Regex.Replace(str1.Trim(), "[^a-z,A-Z,0-9.]", "");
str2 = Regex.Replace(str2.Trim(), "[^a-z,A-Z,0-9.]", "");
return str1 == str2;
}
答案 0 :(得分:4)
没有创建自定义SQL函数就没有简单的方法。这个函数为你提供了一个相当不错的起点:
CREATE FUNCTION dbo.udf_GetNumeric
(@strAlphaNumeric VARCHAR(256))
RETURNS VARCHAR(256)
AS
BEGIN
DECLARE @intAlpha INT
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)
BEGIN
WHILE @intAlpha > 0
BEGIN
SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric )
END
END
RETURN ISNULL(@strAlphaNumeric,0)
END
GO
只需用兼容的like语句替换函数中的模式:
'%[^A-Za-z0-9.,]%'