Extension method in the where section of linq for Entities

In linq to Entities, we need a method that works like "sql like". We implemented our own extension method for IQueryable, because the method does not work for us, because it does not accept templates such as "% a% b%"

Generated Code:

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);
}

This works correctly, and the code is fully executed in SqlServer, but now we will use this extension method inside where where like:

myDBContext.MyObject.Where(o => o.Description.Like(patternToSearch) || o.Title.Like(patterToSerch));

, , where, bool, '||', , , , bool , sqlserver. , BuildLinqExpression bool, , .

! , extensiond Linq Entities, SqlServer? , ?

.

+5
2

, EF , , , EF.

:

  • SqlFunctions EF Where
  • ExpressionVisitor (OrElse/AndAlso) ( , , , a || - , )

.

+3

: fooobar.com/questions/651787/...

: http://pastebin.com/4fMjaCMV

[Expandable] , , linq2entities, . , inline lambdas , , IsCurrent:

static Expression<Func<PropertyHistory, bool>> IsCurrent = (p) => p.Starts <= DateTime.Now;

[ExpandableMethod]
public static IQueryable<PropertyHistory> AsOf(this IQueryable<PropertyHistory> source)
{
  return source.Where(IsCurrent);
}
+2

All Articles