使用实体框架核心进行全文搜索

Hen*_*nry 7 c# entity-framework-core .net-core

使用EFCore进行全文搜索的最佳方法是什么

现在我有两种方法

方法#1

 var entities = this.DbContext.Example
            .FromSql("fullText_Proc {0}, {1}", searchTermParameter, topParameter);

        return entities.AsNoTracking().ToList();
Run Code Online (Sandbox Code Playgroud)

在这里,我被迫创建一个proc,因为FromSql忽略了WHERE子句.

方法#1

创建命令并手动执行映射

using (var command = this.DbContext.Database.GetDbConnection().CreateCommand())
    {
        command.CommandText = "SELECT ... WHERE CONTAINS("Name", @p1)";
        command.CommandType = CommandType.Text;
        var parameter = new SqlParameter("@p1",...);

        this.DbContext.Database.OpenConnection();

        using (var result = command.ExecuteReader())
        {
            while (result.Read())
            {
               .... // Map entity
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

meh*_*ker 5

实际上,WHERE 子句正在与 FromSql 一起使用。我花了足够的时间意识到问题是传递参数。

这就是我解决问题的方法。

  public IList<Example> QueryPhrase(string phrase)
    {
        phrase = $"FORMSOF(FREETEXT, \"{phrase}\")";

        var query = _dataContext.Example
            .FromSql(@"SELECT [Id]
                      ,[Sentence]                          
                    FROM [dbo].[Example]
                    WHERE CONTAINS(Sentence, @p0)", phrase)
            .AsNoTracking();

        return query.ToList();
    }
Run Code Online (Sandbox Code Playgroud)