c# - LINQ to Entities 中的 String.Replace

标签 c# linq linq-to-sql linq-to-entities

我有一个 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/

相关文章:

c# - html 敏捷包对象引用未设置为对象的实例

c# - 方法有数组参数,将数组对象传递给参数

c# - 为什么 LINQ to SQL 不支持查询运算符 'ElementAt'?

javascript - Javascript 延迟执行

c# - 我可以有多个 try block 和一个 catch block 吗

javascript - Visual Studio 2012 中的 '/' 应用程序中的 ASP.NET 服务器错误

linq - 像 SQL 的 linq 查询和 sql server 2008 的 Soudex 是什么?

c# - 短路 Linq for (Count > 1)

unit-testing - 模拟 LINQ To SQL 数据提供程序,实时代码上的 NotSupportedException

c# - SingleOrDefault() 的最佳实践