簡體   English   中英

String.Replace in LINQ to Entities

[英]String.Replace in 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的類。 只有一個實現的方法很重要,其他方法只能是存根:

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());

在應用程序初始化的某個地方。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM