Entity Framework 中使用SQL Server全文索引(Full Text Search)
GitHub:https://github.com/fissoft/Fissoft.EntityFramework.Fts
EntityFramework中原来使用全文索引有些麻烦,需要使用DbContext.Database.SqlQuery或Execute去直接执行SQL。那样不能靠编译来检查读法错误,重构也不方便。
不过EF6增加Interceptor,可以执行前置和后置操作。
Eg:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | 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")));
1 |
分类:
Entity Framework
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异