实体框架中的字符串匹配问题。适用于字符串文字但不适用于字符串变量

Jua*_*esa 5 c# linq entity-framework

我正在尝试使用 C# 中的实体框架从表中获取一行。我有一个名为“TipoPlanta”的表,带有一个名为“Tipo”的主键,它的类型是字符串。

当我尝试使用字符串从表中获取一行时,如果我使用字符串文字,我只能找到一些东西。如果我使用传递给方法的字符串,我找不到任何行。

我有以下方法,其中添加了一些我一直在尝试调试的内容。我传递了字符串 tipoString,在本例中它的值为“Arbol persistente”。这是代码:

        private TipoPlanta getTipoPlanta(String tipoString)
    {
        try
        {
            if (tipoString == "Arbol persistente")
                Console.WriteLine("They are the same");
            else
                Console.WriteLine("They are different");

            var result = (from tar in plantaContext.TipoPlanta where tar.Tipo.Contains(tipoString) select tar);
            var sql = ((System.Data.Objects.ObjectQuery)result).ToTraceString();
            Console.WriteLine("SQL = " + sql);
            Console.WriteLine("RESULT COUNT = " + result.Count());
            Console.WriteLine();

            var resultLiteral = (from tar in plantaContext.TipoPlanta where tar.Tipo.Contains("Arbol persistente") select tar);
            var sql2 = ((System.Data.Objects.ObjectQuery)resultLiteral).ToTraceString();
            Console.WriteLine("SQL2 = " + sql2);
            Console.WriteLine("RESULT LITERAL COUNT = " + resultLiteral.Count());

            TipoPlanta tipo = result.First<TipoPlanta>();
            //              TipoPlanta tipo = (from tar in plantaContext.TipoPlanta where tar.Tipo.Contains("Arbol persistente") select tar).First();
            //TipoPlanta tipo = (from  in plantaContext.TipoPlanta where t.Tipo.CompareTo(tipoString.Trim()) == 0 select t).First();
            return tipo;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            log("Tipo", tipoString, "no existe.");
            return null;
        }
    }
Run Code Online (Sandbox Code Playgroud)

输出是:它们是相同的

SQL = SELECT
[Extent1].[Tipo] AS [Tipo]
FROM [TipoPlanta] AS [Extent1]
WHERE (CHARINDEX(@p__linq__1, [Extent1].[Tipo])) > 0
RESULT COUNT = 0

SQL2 = SELECT 
[Extent1].[Tipo] AS [Tipo]
FROM [TipoPlanta] AS [Extent1]
WHERE (CHARINDEX(N'Arbol persistente', [Extent1].[Tipo])) > 0
RESULT LITERAL COUNT = 1
Run Code Online (Sandbox Code Playgroud)

可以看出,当我使用字符串文字时,它会找到该行,但当我使用我传递的字符串时,即使它们看起来相同,它也会找到行。

有任何想法吗?

kza*_*kza 3

您似乎遇到了编码问题。tipoString 和您的字符串常量在调试器中可能看起来相同,并且 == 可能返回 true,但有一些字符采用不同的编码。

当您将 tipoString 与字符串常量进行比较时,请使用 string.Compare(tipoString, "Arbol persiste", StringComparison.CurrentCulture); 而不是 == 运算符。

正如C# 编程指南中所述:

比较字符串时,应该使用明确指定要执行的比较类型的方法。这使您的代码更易于维护和可读。只要有可能,请使用采用 StringComparison 枚举参数的 System.String 和 System.Array 类的方法重载,以便可以指定要执行的比较类型。比较字符串时最好避免使用 == 和 != 运算符。另外,避免使用 String.CompareTo 实例方法,因为没有任何重载采用 StringComparison。

如果这没有帮助,那么我同意 Daniel 的观点 - 请查看使用 SQL Server Profiler 执行的实际 SQL 语句(假设您的数据在 SQL Server 中)。