如何使用实体框架6执行全文搜索

Edu*_*lva 18 full-text-search entity-framework

我有查询:

var query = DataContext.Fotos.Where(x => x.Pesquisa.Contais("myTerm")
Run Code Online (Sandbox Code Playgroud)

生成的SQL是:

SELECT ... FROM Fotos AS [Extent1] WHERE [Extent1].[Pesquisa] LIKE N'%mytem%'

但我需要使用:

SELECT ... FROM Fotos AS [Extent1] WHERE CONTAINS([Extent1].[Pesquisa],'my term')

如何使用实体框架6执行全文搜索?

Mar*_*Ban 23

似乎Entity Framework 6不支持全文搜索,但有拦截器的解决方法.

http://www.entityframework.info/Home/FullTextSearch

更新链接不起作用,所以这里是原始内容:

Microsoft TSQL通过谓词支持全文查询(CONTAINS和FREETEXT)

例如,您有表Notes

Create table Notes (
    Id int Identity not null,
    NoteText text 
)

CREATE FULLTEXT CATALOG [Notes Data]
Run Code Online (Sandbox Code Playgroud)

当您在此表中搜索包含单词"John"的记录时,您需要发出

SELECT TOP (10) 
* from gps.NOTES
WHERE contains(NoteText, '(john)') 
Run Code Online (Sandbox Code Playgroud)

不幸的是,Enity框架仍然不支持全文搜索谓词.对于EFv6,您可以使用拦截进行解决方法.

这个想法是在内部普通String中包含一些魔术字的搜索文本.包含代码并使用拦截器在SqlCommand中执行sql之前解开它.

首先,让我们创建拦截器类:

public class FtsInterceptor : IDbCommandInterceptor
{
    private const string FullTextPrefix = "-FTSPREFIX-";
    public static string Fts(string search)
    {
    return string.Format("({0}{1})", FullTextPrefix, search);
    }
    public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
    {
    }
    public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
    {
    }
    public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
    {
        RewriteFullTextQuery(command);
    }
    public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
    {
    }
    public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
    {
        RewriteFullTextQuery(command);
    }
    public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
    {
    }
    public static void RewriteFullTextQuery(DbCommand cmd)
    {
        string text = cmd.CommandText;
        for (int i = 0; i < cmd.Parameters.Count; i++)
        {
            DbParameter parameter = cmd.Parameters[i];
            if (parameter.DbType.In(DbType.String, DbType.AnsiString, DbType.StringFixedLength, DbType.AnsiStringFixedLength))
            {
                if (parameter.Value == DBNull.Value)
                    continue;
                var value = (string)parameter.Value;
                if (value.IndexOf(FullTextPrefix) >= 0)
                {
                    parameter.Size = 4096;
                    parameter.DbType = DbType.AnsiStringFixedLength;
                    value = value.Replace(FullTextPrefix, ""); // remove prefix we added n linq query
                    value = value.Substring(1, value.Length - 2); // remove %% escaping by linq translator from string.Contains to sql LIKE
                    parameter.Value = value;
                    cmd.CommandText = Regex.Replace(text,
                    string.Format(
                    @"\[(\w*)\].\[(\w*)\]\s*LIKE\s*@{0}\s?(?:ESCAPE
                    N?'~')",parameter.ParameterName),
                    string.Format(@"contains([$1].[$2], @{0})",parameter.ParameterName));
                    if (text == cmd.CommandText)
                        throw new Exception("FTS was not replaced on: " + text);
                    text = cmd.CommandText;
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用了扩展功能,可以这样定义:

static class LanguageExtensions
{
    public static bool In<T>(this T source, params T[] list)
    {
        return (list as IList<T>).Contains(source);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在让我们编写一个如何使用它的示例.我们需要实体类注意:

public class Note
{
    public int Id { get; set; }
    public string NoteText { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

映射配置:

public class NoteMap : EntityTypeConfiguration<Note>
{
    public NoteMap()
    {
        // Primary Key
        HasKey(t => t.Id);
    }
}
Run Code Online (Sandbox Code Playgroud)

而我们的DbContext祖先:

public class MyContext : DbContext
{
    static MyContext()
    {
        DbInterception.Add(new FtsInterceptor());
    }
    public MyContext(string nameOrConnectionString) : base(nameOrConnectionString)
    {
    }
    public DbSet<Note> Notes { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new NoteMap());
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我们准备好使用它了.让我们搜索'john':

class Program
{
    static void Main(string[] args)
    {
        var s = FtsInterceptor.Fts("john");
        using (var db = new MyContext("CONNSTRING"))
        {
            var q = db.Notes.Where(n => n.NoteText.Contains(s));
            var result = q.Take(10).ToList();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如何使其与数据库优先方法一起使用? (2认同)

Cel*_*gün 5

您可以在 EF 中使用原始 SQL 查询。因此,还有另一种简单的解决方法。

        using (DBContext context = new DBContext())
        {
            string query = string.Format("Select Id, Name, Description From Fotos Where CONTAINS(Pesquisa, '\"{0}\"')", textBoxStrToSearch.Text);
            var data = context.Database.SqlQuery<Fotos>(query).ToList();
            dataGridView1.DataSource = data;
        }
Run Code Online (Sandbox Code Playgroud)

省略了输入验证等。编辑:根据 OP 的查询修改代码。