Entity Framework - case insensitive Contains?

后端 未结 3 1676
离开以前
离开以前 2021-01-03 17:39

I want a solution to this problem that does not involve ToUpper or ToLower, as I use in the code below;

var upper = term.ToUpper();
using (var db = this.Data         


        
相关标签:
3条回答
  • 2021-01-03 18:07

    I know that this is not related directly to EF, but only solution I can think of is to alter DB table column collation to be Case Insensitive e.g.:

    ALTER TABLE TABLENAME ALTER COLUMN COLUMNNAME nvarchar(100) COLLATE Latin1_General_CI_AS NULL
    

    CI - case insensitive / CS - case sensitive

    AS - accent sensitive / AI - accent insensitive (can also be useful)

    If you can't change collation of table column you can use direct query from EF with forcing collation

    select * 
    from table
    where country collate Latin1_General_CI_AS != @country
    
    0 讨论(0)
  • 2021-01-03 18:14

    I use EF6 and Sql Server and Contains is mapped to LIKE '%@p0%' which is case insensitive in my case. So in my case:

    db.Counties.Where(x => x.CountyName.Contains(term)).ToList();
    

    works as needed. More info in Sjoerd answer.

    0 讨论(0)
  • 2021-01-03 18:16

    Just add .ToLower() from upper

     using (var db = this.DataContext)
                {
                    return db.Counties
                           .Where(x => x
                           .CountyName.ToLower()
                           .Contains(upper.ToLower())).ToList();
                }
    
    0 讨论(0)
提交回复
热议问题