c# - Linq to Entity 比较字符串忽略空格

标签 c# entity-framework linq-to-entities

当使用 LINQ to entity 进行字符串比较时,将忽略空格。

在我的表中,我有一个 nchar(10) 列,因此如果它不是 10 个字符,则保存的任何数据都会用空格填充其余部分。下面我将“ncharTextColumn”与 “Four” 字符串进行比较。即使 ncharText 等于 "Four ",它也会导致匹配并且“result”变量将包含 1 条记录

TestEntities1 entity = new TestEntities1();
var result = entity.Table_1.Where(e => e.ncharText == "Four");

是否有对此的解释以及解决它的方法,或者我是否必须在进行任何此类比较之前在我的查询中调用 ToList。

var newList = result.ToList().Where(e => e.ncharText == "Four");

这段代码现在可以正确返回 0 条记录,因为它考虑了空格。但是,在比较之前调用 list 可能会导致将大量集合加载到内存中,而这些集合最终不会被使用。

最佳答案

This答案解释了原因。

SQL Server follows the ANSI/ISO SQL-92 specification (Section 8.2, , General rules #3) on how to compare strings with spaces. The ANSI standard requires padding for the character strings used in comparisons so that their lengths match before comparing them. The padding directly affects the semantics of WHERE and HAVING clause predicates and other Transact-SQL string comparisons. For example, Transact-SQL considers the strings 'abc' and 'abc ' to be equivalent for most comparison operations.

The only exception to this rule is the LIKE predicate. When the right side of a LIKE predicate expression features a value with a trailing space, SQL Server does not pad the two values to the same length before the comparison occurs. Because the purpose of the LIKE predicate, by definition, is to facilitate pattern searches rather than simple string equality tests, this does not violate the section of the ANSI SQL-92 specification mentioned earlier.

在内部,LINQ 只是对您的数据库进行 SQL 查询。

关于c# - Linq to Entity 比较字符串忽略空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23613930/

相关文章:

c# - 如何强制隐藏字段的标签助手以小写形式呈现 bool 值

c# - 如何反序列化没有名称的 JSON.NET 对象?

c# - Entity Framework - 不映射到数据库表的抽象基类

c# - 部署使用 LINQ to Entities 的应用程序

c# - 按相关实体搜索

c# - 使用 LINQ 计数的 UNIQUE 列

c# - 如何使用 LINQ 从 sql 查询编写 linq 查询?

c# - 下面的空条件运算符有什么问题?

c# - 如何创建无限嵌套子菜单?

c# - 带有 EF6 的 System.data.Sqlite