Search code examples
c#linqentity-framework-coreentity

EF Core - Filter a list by category name - ignore casing


I have the following database: enter image description here

I am using navigation properties where possible. My mapping class BookCategory looks like this (I have collection properties in each of the entities - the BookCategories property in the Book class, and the BookCategories property in the Categories class):

public class BookCategory
{
    public int BookId { get; set; }
    public Book Book { get; set; }

    public int CategoryId { get; set; }
    public Category Category { get; set; }
}

I want to get the books by a given list of categories and ignore casing. For example, if we have horror mystery drama as input, we should get the books that are in the horror, mystery, or drama categories (no matter if in the database they are HoRrOR, mYsTERY, DRAMA and vice versa). I am not sure if my idea is good and how to finish it. Thank you advance!

public static string GetBooksByCategory(BookShopContext context, string input)
{
      string[] categories = input.Split(' ', StringSplitOptions.RemoveEmptyEntries);
    
      var books = context.Books
                .Where(b => b.BookCategories.Any(bc => String.Equals(bc.Category.Name, ) ));
}

Solution

  • You need to make sure that your collation are configured correctly (in the database), it's the collation that decides if it's case sensitive or not. This has nothing to do with EF :)

    SQL Server is, by default, case insensitive so if you haven't changed this you should be fine.

    However....

    Collation can be set at multiple levels, so you might need to check all of them:

    • Server level
    • Database level
    • Column level

    Here's a link that shows how to check the collation: https://learn.microsoft.com/en-us/sql/relational-databases/collations/view-collation-information?view=sql-server-ver15

    You can read more here: EF Core 3.0 translating string.Equals ordinalIgnoreCase correctly