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

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

我正在尝试按搜索字符串过滤列表。它说 in the doc on the blue note 那:

我的筛选如下:

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));
}

但是这个解决方案是区分大小写的,我不太明白为什么:因为我使用的是IQueryable,它应该使用数据库提供程序实现,默认情况下不区分大小写,对吧?

我正在使用 EF Core 2,目前只是 运行 本地 MSSQLLocalDB。

您最好使用 LIKE 运算符,例如

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

从 EF Core 2.1 版本开始,您可以使用 HasConversion()。但是数据库中的信息会以小写形式存储:

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

我解决了类似的问题。这个改变解决了我所有的问题。

StringComparison 是我的答案。

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

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

适合我。