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


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM