簡體   English   中英

如何在 ef core 2 中使包含不區分大小寫?

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

我正在嘗試通過搜索字符串過濾列表。 在藍色筆記的文檔中說:

  • IQueryable 為您提供了Contains的數據庫提供程序實現。
  • IEnumerable為您提供了Contains的 .NET Framework 實現
  • SQL Server 實例的默認設置不區分大小寫。
  • 應避免使用ToUpper進行顯式不區分大小寫的調用,因為它會降低性能。

我的過濾如下:

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。

從 EF Core 2.1 版開始,您可以使用 HasConversion()。 但是數據庫中的信息會以小寫形式存儲:

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

我解決了一個類似的問題。 這個改變解決了我所有的問題。

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

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

StringComparison 是我的答案。

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

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

為我工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM