EF动态查询 - 喜欢

时间:2013-09-02 14:15:27

标签: entity-framework expression dynamicquery

使用字符串函数'contains'成功实现了like函数后,我注意到通配符在转换为sql时被转义。

EG。当我搜索以p开头并且其中包含数字13的街道时。我用'%'替换所有空格但EF逃脱它。然后输出查询如下所示:

SELECT " FROM Customer WHERE (LOWER([Street]) LIKE N'%p~%13%' ESCAPE N'~')

在其中一篇博客中,建议使用patindex代替。我只是不知道如何实现这一点。

我目前的代码如下:

public static Expression<Func<T, bool>> Create<T>(string propertyName, ComparisonOperators comparisonOperator, dynamic comparedValue1, dynamic comparedValue2 = null)
{
    ParameterExpression parameterExpression = Expression.Parameter(typeof(T), "x");
    MemberExpression memberExpression = Expression.MakeMemberAccess(parameterExpression, typeof(T).GetProperty(propertyName));
    ConstantExpression constantExpression = Expression.Constant(comparedValue1, comparedValue1.GetType());
    Expression expressionBody = null;

    switch (comparisonOperator)
    {
        ...

        case ComparisonOperators.Contains:
            expressionBody = Expression.Call(GetLowerCasePropertyAccess(memberExpression), ContainsMethod, Expression.Constant(comparedValue1.ToLower()));
            break;
    }

    return Expression.Lambda<Func<T, bool>>(expressionBody, new ParameterExpression[] { parameterExpression });
}

private static MethodCallExpression GetLowerCasePropertyAccess(MemberExpression propertyAccess)
{
    var stringExpression = GetConvertToStringExpression(propertyAccess);
    if (stringExpression == null)
        throw new Exception(string.Format("Not supported property type {0}", propertyAccess.Type));

    return Expression.Call(stringExpression, typeof(string).GetMethod("ToLower", Type.EmptyTypes));
}

private static Expression GetConvertToStringExpression(Expression e)
{
    // if property string - no cast needed
    // else - use SqlFunction.StringConvert(double?) or SqlFunction.StringConvert(decimal?);
    Expression strExpression = null;
    if (e.Type == typeof(string)) strExpression = e;
    else
    {
        var systemType = Nullable.GetUnderlyingType(e.Type) ?? e.Type;
        if (systemType == typeof(int) || systemType == typeof(long) || systemType == typeof(double) || systemType == typeof(short) || systemType == typeof(byte))
        {
            // cast int to double
            var doubleExpr = Expression.Convert(e, typeof(double?));
            strExpression = Expression.Call(StringConvertMethodDouble, doubleExpr);
        }
        else if (systemType == typeof(decimal))
        {
            // call decimal version of StringConvert method
            // cast to nullable decimal
            var decimalExpr = Expression.Convert(e, typeof(decimal?));
            strExpression = Expression.Call(StringConvertMethodDecimal, decimalExpr);
        }
    }
    return strExpression;
}

private static readonly MethodInfo ContainsMethod = typeof(String).GetMethod("Contains", new Type[] { typeof(String) });
private static readonly MethodInfo StringConvertMethodDouble = typeof(SqlFunctions).GetMethod("StringConvert", new Type[] { typeof(double?) });
private static readonly MethodInfo StringConvertMethodDecimal = typeof(SqlFunctions).GetMethod("StringConvert", new Type[] { typeof(decimal?) });

1 个答案:

答案 0 :(得分:0)

像这样:

ctx.Products.Where(x => SqlFunctions.PatIndex("%Something%", x.Name) > 1).ToList();

但这与:

相同
ctx.Products.Where(x => x.Name.Contains("Something")).ToList();