【发布时间】:2021-08-16 09:43:12
【问题描述】:
我正在尝试编写一个处理全文搜索的 Sql 扩展方法。
public static class StringSearchExtensions
{
public static IQueryable<T> SearchByWords<T>(this IQueryable<T> query, string pattern)
{
var tokens = pattern
.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
return tokens.Aggregate(query, (current, token) =>
current.Where(x=>
PgSql.Ilike(x.TextField, $"%{token}%")));
}
}
TextField 是我需要从调用代码中指定的字段。
PgSql是我的另一个扩展类,包含Ilike方法,它只是应用了psql的ILike方法。
我需要将参数x=>x.Textfield 与我的参数一起传递。
【问题讨论】:
-
真正的问题是什么?这个函数怎么调用?
-
对了,你知道DbFunctions.Like和SqlMethods.Like吗?也许这符合您的需求。
-
的限制呢? public static IQueryable<T> SearchByWords<T>(this IQueryable<T> query, string pattern) where T: ITextFieldContained -
通常你会使用“表达式”,比如
Expression<Func<T, string>>,以便能够将该方法转换为等效的 SQL,但我不知道它是否可以与类似查询一起使用,因为它似乎期望一个实际的字符串。 -
@JonasH 是的,你是对的,这就是我想要做的,但遗憾的是,它不起作用。
标签: c# iqueryable