问题
当我使用 Linq 写入实体时
context.MyTable.Where(t => t.Name == "Test");
它转换为以下 sql:
select * from MyTable where Name = 'Test'
我想在 Linq 中为将转换为的实体编写一个表达式:
select * from MyTable where Name like 'Test'
有什么方法可以实现吗?
注意 - 我还尝试了 Equals
和 CompareTo == 0
但无济于事。
背景故事
我想使用 Like
而不是 =
的原因是,如果使用 =,字符串末尾的空格将被忽略
,但如果您使用 Like
(请参阅这个问题:Why the SQL Server ignore the empty space at the end automatically?,还有这个:Linq to Entity comparing strings ignores white spaces)。
编辑:为什么它不是 How to do SQL Like % in Linq? 的副本
这个问题要求像 %,这可以用 Contains/StartsWith/EndsWith
来完成,但这不是同一个问题,我想要完全平等,所以那些对我没有帮助。
虽然使用 SqlMethods.Like
对这个问题有一个看起来很有希望的答案,所以我尝试了
context.MyTable.Where(t => SqlMethods.Like(t.Name, "Test")
但是我得到了以下错误:
{"LINQ to Entities does not recognize the method 'Boolean Like(System.String, System.String)' method, and this method cannot be translated into a store expression."}
最佳答案
是official :
SQL Server follows the ANSI/ISO SQL-92 specification (Section 8.2, , General rules #3) on how to compare strings with spaces.
如果你不想要它,那就太麻烦了。
一个不忽略空格的 SQL 函数是 DATALENGTH
。幸运的是,我们可以在 EF 查询中使用这个函数,因为它是 SqlFunctions
中的函数之一。 .因此,您可以添加一个额外的检查 DATALENGTH
是否等于搜索字符串的长度:
var searchText = "Test";
var result = context.MyTable
.Where(t => t.Name == searchText
&& SqlFunctions.DataLength(t.Name)
== SqlFunctions.DataLength(searchText))
比较 t.Name
和 searchText
的 DataLength
是必要的,因为 DataLength
返回字节数,不是字符数(Ivan,感谢您的评论)。
关于c# - 如何告诉 Linq to Entities 使用 'Like' 来实现字符串相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39300790/