简体   繁体   English

如何在 ef core 2 中使包含不区分大小写?

[英]How do I make contains case-insensitive in ef core 2?

I am trying to filter a list by a search string.我正在尝试通过搜索字符串过滤列表。 It says in the doc on the blue note that:在蓝色笔记的文档中说:

  • IQueryable gives you the database provider implementation of Contains . IQueryable 为您提供了Contains的数据库提供程序实现。
  • IEnumerable gives you the .NET Framework implementation of Contains IEnumerable为您提供了Contains的 .NET Framework 实现
  • The default setting of SQL Server instances is case-insensitive. SQL Server 实例的默认设置不区分大小写。
  • Using ToUpper to make an explicit case-insensitive call should be avoided because it has a performance penalty.应避免使用ToUpper进行显式不区分大小写的调用,因为它会降低性能。

My filtering is as follows:我的过滤如下:

IQueryable<ApplicationUser> customers = 
    from u in _context.Users
    where (u.Customer != null && u.IsActive)
    select u;

if (!string.IsNullOrEmpty(searchString))
{
    customers = customers.Where(s => s.Email.Contains(searchString));
}

This solution however is case-sensitive, and I don't really understand why: since I'm using IQueryable , it should use the database provider implementation, that is case-insensitive by default, right?然而,这个解决方案区分大小写,我真的不明白为什么:因为我使用的是IQueryable ,它应该使用数据库提供程序实现,默认情况下不区分大小写,对吧?

I'm using EF Core 2 and currently just running a local MSSQLLocalDB.我正在使用 EF Core 2,目前只运行本地 MSSQLLocalDB。

starting from version 2.1 of the EF Core, you can use HasConversion().从 EF Core 2.1 版开始,您可以使用 HasConversion()。 But the information in the database will be stored in lowercase:但是数据库中的信息会以小写形式存储:

builder.Property(it => it.Email).HasConversion(v => v.ToLowerInvariant(), v => v);

I solved a similar problem.我解决了一个类似的问题。 This change solved all my problems.这个改变解决了我所有的问题。

You would be better off using LIKE operator, eg您最好使用LIKE运算符,例如

if (!String.IsNullOrEmpty(searchString))
{
    customers = customers.Where(x => EF.Functions.Like(x.Email, $"%{searchString}%"));
}

StringComparison is answer for me. StringComparison 是我的答案。

customers = customers.Where(s => s.Email.Contains(searchString, StringComparison.CurrentCultureIgnoreCase));客户 =customers.Where(s => s.Email.Contains(searchString, StringComparison.CurrentCultureIgnoreCase));

OR

customers = customers.Where(s => s.Email.Contains(searchString, StringComparison.InvariantCultureIgnoreCase));客户 = customers.Where(s => s.Email.Contains(searchString, StringComparison.InvariantCultureIgnoreCase));

works for me.为我工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM