实体框架 EF.Functions.Like 与 string.Contains [英] Entity framework EF.Functions.Like vs string.Contains
问题描述
我正在阅读实体框架核心 2.0 的公告 https://blogs.msdn.microsoft.com/dotnet/2017/08/14/announcing-entity-framework-core-2-0/
I was reading the announcement of entity framework core 2.0 https://blogs.msdn.microsoft.com/dotnet/2017/08/14/announcing-entity-framework-core-2-0/
据说他们添加了新的 Sql 函数,例如 EF.Functions.Like
来执行 SQL LIKE
操作.
It says that they added new Sql functions like EF.Functions.Like
for performing the SQL LIKE
operation.
我想知道,EF.Functions.Like
和 string.Contains
/StartsWith
之间有什么区别?
I was wondering, what then would be the difference between EF.Functions.Like
and string.Contains
/StartsWith
?
例如:
var customers = context.Customers.Where(c => c.Name.StartsWith("a")); // Version A
var customers = context.Customers.Where(c => EF.Functions.Like(c.Name, "a%")); // Version B
这两个版本有什么区别?EF 已经知道如何将 string.Contains
/StartsWith
翻译成相应的 SQL 操作,不是吗?
What would be the difference between the two versions?
EF already knows how to translate string.Contains
/StartsWith
to the corresponding SQL operations, doesn't it?
我能想到的唯一原因是 EF.Functions.Like 将允许更复杂的模式,如 "a%b%"
(虽然这个可以写成 StartsWith("a") &&包含("b")
)
The only reason i can think of is that EF.Functions.Like would allow for more complex patterns like "a%b%"
(although this one can be written as StartsWith("a") && Contains("b")
)
是这个原因吗?
推荐答案
Like 查询支持通配符 因此在某些情况下与字符串扩展方法相比非常有用.
Like query supports wildcard characters and hence very useful compared to the string extension methods in some scenarios.
例如:如果我们要搜索所有以 'ri' 作为中间字符的 4 个字母名称,我们可以执行 EF.Functions.Like(c.Name, "_ri_");
For ex: If we were to search all the 4 lettered names with 'ri' as the middle characters we could do EF.Functions.Like(c.Name, "_ri_");
或者从以元音开头的城市获取所有客户:
or to get all the customers from cities which start with vowels:
var customers = from c in context.Customers
where EF.Functions.Like(c.City, "[aeiou]%")
select c;
(请阅读@Tseng 的回答,了解它们如何以不同的方式转换为 SQL 查询)
(Please read @Tseng's answer on how they are translated differently into SQL queries)
这篇关于实体框架 EF.Functions.Like 与 string.Contains的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!