在 linq to Entities 中,我们需要一种类似于“sql like”的方法。我们已经实现了我们自己的 IQueryable 扩展方法,因为 contains 方法对我们不起作用,因为它不接受像 '%a%b%' 这样的模式
创建的代码是:
private const char WildcardCharacter = '%';
public static IQueryable<TSource> WhereLike<TSource>(this IQueryable<TSource> _source, Expression<Func<TSource, string>> _valueSelector, string _textSearch)
{
if (_valueSelector == null)
{
throw new ArgumentNullException("valueSelector");
}
return _source.Where(BuildLikeExpressionWithWildcards(_valueSelector, _textSearch));
}
private static Expression<Func<TSource, bool>> BuildLikeExpressionWithWildcards<TSource>(Expression<Func<TSource, string>> _valueSelector, string _textToSearch)
{
var method = GetPatIndexMethod();
var body = Expression.Call(method, Expression.Constant(WildcardCharacter + _textToSearch + WildcardCharacter), _valueSelector.Body);
var parameter = _valueSelector.Parameters.Single();
UnaryExpression expressionConvert = Expression.Convert(Expression.Constant(0), typeof(int?));
return Expression.Lambda<Func<TSource, bool>> (Expression.GreaterThan(body, expressionConvert), parameter);
}
private static MethodInfo GetPatIndexMethod()
{
var methodName = "PatIndex";
Type stringType = typeof(SqlFunctions);
return stringType.GetMethod(methodName);
}
这可以正常工作,并且代码完全在 SqlServer 中执行,但现在我们将在 where 子句中使用此扩展方法,如下所示:
myDBContext.MyObject.Where(o => o.Description.Like(patternToSearch) || o.Title.Like(patterToSerch));
问题是,如果与“||”等运算符一起使用,where 子句中使用的方法必须返回 bool 结果,而且我不知道如何使我创建的代码返回 bool 并保持代码在 sqlserver 中执行。我想我必须将 BuildLinqExpression 方法返回的表达式转换为 bool,但我不知道该怎么做
总结!首先,是否可以在 Linq to Entities 中创建自己的扩展方法来执行 Sql Server 中的代码?如果这可能的话我该怎么做?
感谢您的帮助。