简体   繁体   中英

String.Replace in LINQ to Entities

I have an Asp.Net MVC 5 website and I want to search entities using LINQ. Currently I have a working search function. However, I want to add a feature which replaces characters in strings before running the search. This is due to the fact that in Farsi, there are two similar representations of a single character and I want to run the search for both of them.

The working code is this (a very simplified version):

var model = db.Restaurants.Where(r => r.Name.ToUpper().Contains(query));

what I want to do is this:

query = query.Replace('آ', 'ا'); //couple of other fixes too...
var model = db.Restaurants.Where(r => r.Name.ToUpper().Replace('آ', 'ا').Contains(query));

Obviously, this gives me the error:

LINQ to Entities does not recognize the method 'System.String Replace(Char, Char)' method, and this method cannot be translated into a store expression

Currently the only thing that comes to my mind is to store the replaced strings into database and query those strings. This is not a clean approach in my opinion. Another option is to run the query in code (query Restaurant s one by one) which isn't efficient at all. Caching those values is going to help but again, I think there's a better way. That's why I asked this question to see if there is some way to transfer this query to database.

In Entity Framework 6 you can use command interceptors. It sounds complicated, but they've made it easy as pie.

First create a class that implements System.Data.Entity.Infrastructure.Interception.IDbCommandInterceptor . Only one implemented method matters, the others can just be stubs:

public class MyCommandInterceptor : IDbCommandInterceptor
{
    public void ReaderExecuting(DbCommand command,
                DbCommandInterceptionContext<DbDataReader> interceptionContext)
    {
        command.CommandText = command.CommandText.Replace("a", "b");
    }

    public void NonQueryExecuting(DbCommand command, 
                DbCommandInterceptionContext<int> interceptionContext)
    { }

    ... lots of stubs
}

And you activate the interceptor by calling

DbInterception.Add(new MyCommandInterceptor());

somewhere in the initialization of you application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM