Base solution for your next web application
Open Closed

Using .Contains in WhereIf clause and case sensitivity #12335


User avatar
0
uenlkr4e created

Hi, I have the following query:

var query = _recipientRepository.GetAll()
            .WhereIf(!string.IsNullOrEmpty(input.Keyword), x => x.Name.Contains(input.Keyword) || x.LastName.Contains(input.Keyword)
                 || x.Title.Contains(input.Keyword));

I thought .Contains was not case sensitive but it seems like it is. I am using postgresql so it maybe postgre related. Is there an easy way to turn ".contains" calls to case insensitive without going through each one and adding toLower()?

thank you

Markdown is supported
Copy & paste or drag & drop images (max 30 MB per image)

1 Answer(s)
  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi @uenlkr4e

    • If you're using postgresql, you can replace Contains() with EF.Functions.ILike(). This maps directly to the postgresql ILIKE operator, which performs case insensitive string comparisons.

    Example

    var query = _recipientRepository.GetAll()
        .WhereIf(!string.IsNullOrEmpty(input.Keyword), x =>
            EF.Functions.ILike(x.Name, $"%{input.Keyword}%") ||
            EF.Functions.ILike(x.LastName, $"%{input.Keyword}%") ||
            EF.Functions.ILike(x.Title, $"%{input.Keyword}%"));
    
    • You can create a custom extension method to make it case insensitive. This way, you don’t need to modify your existing queries too much. You can call ContainsIgnoreCase instead of Contains.

    • Example

    public static class QueryableExtensions
    {
        public static bool ContainsIgnoreCase(this string source, string toCheck)
        {
            return source != null && toCheck != null && source.IndexOf(toCheck, StringComparison.OrdinalIgnoreCase) >= 0;
        }
    }
    
    
    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)