Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Full-Text Search with Entity Framework Core

What is the best way to use full-text search with EFCore

For now I have two approaches

Approach #1

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

        return entities.AsNoTracking().ToList();

Here I'm forced to create a proc because FromSql ignores the WHERE clause.

Approach #1

Create a command and do the mapping manually

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
            }
        }
    }
like image 473
Henry Avatar asked Jul 23 '17 06:07

Henry


1 Answers

WHERE clause is working with FromSql, actually. I spent enough time to realize problem was passing parameter.

This is how I have solved the problem.

  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();
    }
like image 80
mehmetilker Avatar answered Sep 21 '22 01:09

mehmetilker