How to search string using Entity Framework with .Contains and with accent-insensitive

喜夏-厌秋 提交于 2019-12-12 15:33:50

问题


In my database, I have a table that stores cities. Some cities have accents like "Foz do Iguaçu".

In my MVC application, I have a JSON that return a list of cities based in a word, however, few users aren't using accents to search for the city, for example "Foz do Iguacu".

in my database I have "Foz do IguaÇu" but users users searches for "Foz do IguaCu"

How can I search records in my table, ignoring accents?

Here is my code:

    using (ServiciliEntities db = new ServiciliEntities())
    {
        List<Cidades> lCidades = db.Cidades.Where(c => c.CidNome.ToLower().Contains(q.Trim().ToLower())).OrderBy(c => c.CidNome).Take(10).ToList();
        ArrayList lNomes = new ArrayList();
        foreach (Cidades city in lCidades)
            lNomes.Add(new {city.CidNome, city.Estados.EstNome});

        return Json(new { data = lNomes.ToArray() });
    }

回答1:


You can set accent-insensitive collation order on the column in database. The query then should work. For example, if you set SQL_LATIN1_GENERAL_CP1_CI_AI to the CidNome column, query will perform as wanted.

Use this SQL script:

ALTER TABLE dbo.YourTableName
ALTER COLUMN YourColumnName NVARCHAR (100) COLLATE SQL_Latin1_General_CP1_CS_AS NULL



回答2:


The solution is the following:

ALTER TABLE dbo.YourTableName
ALTER COLUMN YourColumnName NVARCHAR (100) COLLATE SQL_Latin1_General_CP1_CI_AI NULL

Where LATIN1_GENERAL means English (US), CI means Case-Insensitive and AI means Accent-Insensitive.



来源:https://stackoverflow.com/questions/33722136/how-to-search-string-using-entity-framework-with-contains-and-with-accent-insen

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