我有一个 Asp.Net MVC 5 网站,我想使用 LINQ 搜索实体。目前我有一个有效的搜索功能。但是,我想添加一个功能,在运行搜索之前替换字符串中的字符。这是因为在波斯语中,单个字符有两种相似的表示形式,我想对它们都进行搜索。
工作代码是这样的(一个非常简化的版本):
var model = db.Restaurants.Where(r => r.Name.ToUpper().Contains(query));
我想做的是:
query = query.Replace('آ', 'ا'); //couple of other fixes too...
var model = db.Restaurants.Where(r => r.Name.ToUpper().Replace('آ', 'ا').Contains(query));
显然,这给了我错误:
LINQ to Entities does not recognize the method 'System.String Replace(Char, Char)' method, and this method cannot be translated into a store expression
目前我唯一想到的是将替换的字符串存储到数据库中并查询这些字符串。在我看来,这不是一个干净的方法。另一种选择是在代码中运行查询(逐个查询 Restaurant
),这根本没有效率。缓存这些值会有所帮助,但我认为还有更好的方法。这就是为什么我问这个问题,看看是否有某种方法可以将此查询传输到数据库。
最佳答案
在 Entity Framework 6 中,您可以使用命令拦截器。这听起来很复杂,但他们把它变得很简单。
首先创建一个实现 System.Data.Entity.Infrastructure.Interception.IDbCommandInterceptor
的类。只有一个实现的方法很重要,其他的可以只是 stub :
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
}
然后您通过调用激活拦截器
DbInterception.Add(new MyCommandInterceptor());
在您的应用程序初始化的某处。
关于c# - LINQ to Entities 中的 String.Replace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21902142/