码迷,mamicode.com
首页 > 数据库 > 详细

Entity Framework 中使用SQL Server全文索引(Full Text Search)

时间:2015-01-12 16:25:08      阅读:860      评论:0      收藏:0      [点我收藏+]

标签:

GitHub:https://github.com/fissoft/Fissoft.EntityFramework.Fts

 

EntityFramework中原来使用全文索引有些麻烦,需要使用DbContext.Database.SqlQuery或Execute去直接执行SQL。那样不能靠编译来检查读法错误,重构也不方便。

不过EF6增加Interceptor,可以执行前置和后置操作。

Eg:

 public class FtsInterceptor : IDbCommandInterceptor
    {
        #region interface impl

        public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
        }

        public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
        }

        public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
        {
        }

        public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
        {
        }

        public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
          
        }

        public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
        }

        #endregion
}

  与Filter或其它Aop框架差不多,这里提供了一共6个方法,分别是在ScalarExecute,NonQueryExecute,ReaderExecute 这三种查询 前置及后置操作

一般来说,使用全文索引是为了查询数据,所以ScalarExecute,ReaderExecute这两种查询的前置方法需要我们改写,具体改写的原理是,将DbCommand中的CommandText读取出来,然后处理成支持全文索引的格式。

细节请参考GitHub的代码:https://github.com/fissoft/Fissoft.EntityFramework.Fts

使用时按以下方法即可

1.通过Nuget引用,或下载GitHub上的代码编译

PM> Install-Package Fissoft.EntityFramework.Fts

2.然后在程序启动时执行以下读句添加拦截器

    DbInterceptors.Init()

3.执行查询时可以使用以下几种方法

    db.Tables.Where(c=>c.Fullname.Contains(FullTextSearchModelUtil.Contains("code")));
    db.Tables.Where(c=>c.Fullname.FreeText(FullTextSearchModelUtil.Contains("code ef")));
    db.Tables.Where(c=>"*".Contains(FullTextSearchModelUtil.ContainsAll("code ef")));
    db.Tables.Where(c=>"*".Contains(FullTextSearchModelUtil.FreeTextAll("code ef")));

Entity Framework 中使用SQL Server全文索引(Full Text Search)

标签:

原文地址:http://www.cnblogs.com/chsword/p/ef_fts.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!