Entity Framework - case insensitive Contains?

落花浮王杯 提交于 2020-01-21 03:55:05

问题


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.DataContext)
{
    return db.Counties.Where(x => x.CountyName.ToUpper().Contains(upper)).ToList();
}

I am using entitly framework so the C# solution of using StringComparison.CurrentCultureIgnoreCase does not work. It does work for Equals, EndsWith and StartsWith, but not Contains.


回答1:


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.




回答2:


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



回答3:


Just add .ToLower() from upper

 using (var db = this.DataContext)
            {
                return db.Counties
                       .Where(x => x
                       .CountyName.ToLower()
                       .Contains(upper.ToLower())).ToList();
            }


来源:https://stackoverflow.com/questions/14400856/entity-framework-case-insensitive-contains

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!