LINQ到实体比较字符串忽略空格 [英] Linq to Entity comparing strings ignores white spaces

查看:519
本文介绍了LINQ到实体比较字符串忽略空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用LINQ to实体做字符串比较会忽略空格。

When using linq to entity doing string comparisons will ignore white spaces.

在我的表我有一个NCHAR(10)列,如果它不是那么任何数据保存10个字符将填补剩下的空的空间。下面我对四有字符串比较ncharTextColumn。甚至想到了ncharText将等于四有这导致比赛和结果变量将包含1记录

In my table i have an nchar(10) column so any data saved if it is not 10 characters will fill the rest with empty spaces. Below i am comparing the "ncharTextColumn" with the "Four" string. And even thought the ncharText will equal "Four " It results in a match and the "result" variable will contain 1 record

        TestEntities1 entity = new TestEntities1();

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



对此有一个解释,并解决它还是我将不得不调用方式。对了ToList像这样的任何comaprisons之前我的查询

Is there an explanation for this and a way to work around it or am i going to have to call ToList on my query before any comaprisons like so.

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

此代码现在可以正确地返回0的记录,因为它考虑到空格。但是打电话来列出一个比较之前可能会导致装载大量收集到内存中,不会最终被使用。

This code now correctly returns 0 records as it takes into account white spaces. However calling to list before a comparison can result in loading a large collection into memory which won't end up being used.

推荐答案

回答解释了原因。

SQL Server遵循了ANSI / ISO SQL-92规范对如何使用字符串比较的空间(第8.2节,
一般规则#3)。在ANSI
标准要求为
比较中使用的字符串,这样比较它们之前,它们的长度匹配填充。在
填充直接影响的语义WHERE和HAVING子句
谓词和其它Transact-SQL字符串比较。例如,
的Transact-SQL认为字符串ABC和ABC是大多数比较操作相当于

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.

唯一的例外这个规则是LIKE谓词。当LIKE谓词表达式的右侧
侧设有一个尾随
空间中的值时,SQL Server比较发生之前没有垫两个值相同的长度
。因为LIKE
谓之目的,顾名思义,是为了方便模式搜索,而
不是简单的字符串相等测试,这并不违反前面提到的ANSI SQL-92规范的部分

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查询你的数据库。

Internally LINQ is just making SQL queries against your database.

这篇关于LINQ到实体比较字符串忽略空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆