【问题标题】:How to do a string compare using regex and linq to sql如何使用正则表达式和 linq to sql 进行字符串比较
【发布时间】:2017-09-23 15:12:45
【问题描述】:

以下代码失败并出现错误:

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;
}

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    没有创建自定义 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
    

    https://blog.sqlauthority.com/2008/10/14/sql-server-get-numeric-value-from-alpha-numeric-string-udf-for-get-numeric-numbers-only/

    只需将函数中的模式替换为兼容的like语句即可:

    '%[^A-Za-z0-9.,]%'
    

    你可以call a user defined function from LINQ to SQL

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多