您的位置:首页 > 数据库

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

2015-01-12 15:26 597 查看
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")));



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: