Ignoring accents while searching the database using Entity Framework

心不动则不痛 提交于 2019-11-29 13:30:21

If you set an accent-insensitive collation order on the Name column then the queries should work as required.

Setting an accent-insensitive collation will fix the problem.

You can change the collation for a column in SQL Server and Azure database with the next query.

ALTER TABLE TableName
ALTER COLUMN ColumnName NVARCHAR (100)
COLLATE SQL_LATIN1_GENERAL_CP1_CI_AI NOT NULL

SQL_LATIN1_GENERAL_CP1_CI_AI is the collation where LATIN1_GENERAL is English (United States), CP1 is code page 1252, CI is case-insensitive, and AI is accent-insensitive.

jgasiorowski

I know that is not so clean solution, but after reading this I tried something like this:

var query = this.DataContext.Users.SqlQuery(string.Format("SELECT *  FROM dbo.Users WHERE LastName like '%{0}%' COLLATE Latin1_general_CI_AI", parameters.SearchTerm));

After that you are still able to call methods on 'query' object like Count, OrderBy, Skip etc.

ordag

Accent-insensitive Collation as Stuart Dunkeld suggested is definitely the best solution ...

But maybe good to know:

Michael Kaplan once posted about stripping diacritics:

static string RemoveDiacritics(string stIn)
{
    string stFormD = stIn.Normalize(NormalizationForm.FormD);
    StringBuilder sb = new StringBuilder();

    for(int ich = 0; ich < stFormD.Length; ich++)
    {
        UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);
        if(uc != UnicodeCategory.NonSpacingMark)
        {
            sb.Append(stFormD[ich]);
        }
    }

    return(sb.ToString().Normalize(NormalizationForm.FormC));
}

Source

So your code would be:

myEntities.Items.Where(i => RemoveDiacritics(i.Name).Contains("a")); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!