Linq 中没有内置全文搜索,而且似乎没有很多关于该主题的帖子,所以我玩了一下,并为我的实用类想出了这个方法:
public static IEnumerable<TSource> GenericFullTextSearch<TSource>(string text, MyDataContext context)
{
//Find LINQ Table attribute
object[] info = typeof(TSource).GetCustomAttributes(typeof(System.Data.Linq.Mapping.TableAttribute), true);
//Get table name
String table = (info[0] as System.Data.Linq.Mapping.TableAttribute).Name;
//Full text search on that table
return context.ExecuteQuery<TSource>(String.Concat("SELECT * FROM ", table, " WHERE CONTAINS(*, {0})"), text);
}
并将这个包装器添加到每个有全文索引的部分 Linq 类中
public static IEnumerable<Pet> FullTextSearch(string text, MyDataContext context)
{
return (LinqUtilities.GenericFullTextSearch<Pet>(text, context) as IEnumerable<Pet>);
}
所以现在我可以使用整洁的东西进行全文搜索,例如
var Pets = Pet.FullTextSearch(helloimatextbox.Text, MyDataContext).Skip(10).Take(10);
我假设目前只需要非常基本的搜索。任何人都可以改进吗?是否可以实现为扩展方法并避免使用包装器?
最佳答案
最简洁的解决方案是在 sql 中使用内联表值函数并将其添加到您的模型中
http://sqlblogcasts.com/blogs/simons/archive/2008/12/18/LINQ-to-SQL---Enabling-Fulltext-searching.aspx
To get it working you need to create a table valued function that does nothing more than a
CONTAINSTABLE
query based on the keywords you pass in,create function udf_sessionSearch (@keywords nvarchar(4000)) returns table as return (select [SessionId],[rank] from containstable(Session,(description,title),@keywords))
You then add this function to your LINQ 2 SQL model and he presto you can now write queries like.
var sessList = from s in DB.Sessions join fts in DB.udf_sessionSearch(SearchText) on s.sessionId equals fts.SessionId select s;
关于linq - Linq 中的全文搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/565617/