1

I created extension method that Remove Diacritics, in Helper method class,

namespace MvcCms.Models.Utilities
{
    public static class HelperMethods
    {
            public static string RemoveDiacritics(this 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));
            }
        }
    }

and i created a controller that have Json result action searching for the terms without diacritics,

using MvcCms.Models.Utilities;

namespace MvcCms.Controllers
{
    public class AjaxController : ControllerHelper
    {
        public JsonResult AutoCompleteCategories(string term, int id)
        {
            string termWithoutDiacritics = term.RemoveDiacritics();
            var searchResult = db.C_Categories.Where(x => x.CatVocId == id && (x.Title.RemoveDiacritics().ToUpper().Contains(term.ToUpper()) || x.Title.ToUpper().Contains(termWithoutDiacritics.ToUpper())));
            var jsonResult = searchResult.Select(results => new { id = results.CatId, name = results.Title });

            return Json(jsonResult, JsonRequestBehavior.AllowGet);
        }
    }
} 

when i run the code, it gives me error : LINQ to Entities does not recognize the method 'System.String RemoveDiacritics(System .String)' method, and this method cannot be translated into a store expression

Ahmad Alaa
  • 767
  • 9
  • 30
  • See also [Ignoring accents while searching the database using Entity Framework](http://stackoverflow.com/questions/6357351/ignoring-accents-while-searching-the-database-using-entity-framework/6357748#6357748) – Ivan Stoev May 05 '16 at 09:45

1 Answers1

2

It is because LINQ to Entities does not recognize the method 'System.String RemoveDiacritics(System .String)' method, and this method cannot be translated into a store expression. LINQ to Entities tries to translate your query to a language which your data provider supports (usually SQL). Since your query has a call to RemoveDiacritics and it can not be translated like this you get the error.

You can fetch the data into memory and then apply your method on it via LINQ to Objects. This approach can cause serious performance problems. Use it wisely.

var items = db.C_Categories.Where(x => x.CatVocId == id).ToList();
var searchResult = items.Where(x =>  x.Title.RemoveDiacritics().ToUpper().Contains(term.ToUpper()) ||
                                     x.Title.ToUpper().Contains(termWithoutDiacritics.ToUpper()));
Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74