Ignoring accents while searching the database using Entity Framework

后端 未结 4 1663
长发绾君心
长发绾君心 2020-12-11 15:23

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 s

相关标签:
4条回答
  • 2020-12-11 15:37

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

    0 讨论(0)
  • 2020-12-11 15:45

    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.

    0 讨论(0)
  • 2020-12-11 15:45

    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.

    0 讨论(0)
  • 2020-12-11 15:56

    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")); 
    
    0 讨论(0)
提交回复
热议问题