Ignoring accents while searching the database using Entity Framework

≡放荡痞女 提交于 2019-11-28 07:08:44

问题


I have a database table that contains names with accented characters. Like ä and so on.

I need to get all records using EF4 from a table that contains some substring regardless of accents.

So the following code:

myEntities.Items.Where(i => i.Name.Contains("a")); 

should return all items with a name containing a, but also all items containing ä, â and so on. Is this possible?


回答1:


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




回答2:


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.




回答3:


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.




回答4:


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")); 


来源:https://stackoverflow.com/questions/6357351/ignoring-accents-while-searching-the-database-using-entity-framework

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