在Expression树中调用lambda表达式

时间:2014-06-27 16:05:52

标签: c# lambda expression-trees linq-expressions

我有一个SelectionCriteria类,我用它来构建基于PredicateBuilder的Entity Framework查询表达式。在其范围内,它工作正常。我想扩展它,以便它可以查询字段是否包含子字符串。我的问题是我无法看到如何构建所需的表达式对象。

我的实际课程支持和,或者,而不是,但它们与我的问题无关。所以我简化了我的示例代码,只处理一个二进制操作:

public class SelectionCriteria
{
    public SelectionComparison selectionComparison { get; set; }
    public string fieldName { get; set; }
    public object fieldValue { get; set; }

    public Expression<Func<T, bool>> constructSinglePredicate<T>()
    {
        var type = typeof(T);

        if (type.GetProperty(this.fieldName) == null && type.GetField(this.fieldName) == null)
            throw new MissingMemberException(type.Name, this.fieldName);

        ExpressionType operation;
        if (!operationMap.TryGetValue(this.selectionComparison, out operation))
            throw new ArgumentOutOfRangeException("selectionComparison", this.selectionComparison, "Invalid filter operation");

        var parameter = Expression.Parameter(type);
        var member = Expression.PropertyOrField(parameter, this.fieldName);
        var value = (this.fieldValue == null) ? Expression.Constant(null) : Expression.Constant(this.fieldValue, this.fieldValue.GetType());

        try
        {
            var converted = (value.Type != member.Type)
                ? (Expression) Expression.Convert(value, member.Type)
                : (Expression) value;

            var comparison = Expression.MakeBinary(operation, member, converted);

            var lambda = Expression.Lambda<Func<T, bool>>(comparison, parameter);

            return lambda;
        }
        catch (Exception)
        {
            throw new InvalidOperationException(
                String.Format("Cannot convert value \"{0}\" of type \"{1}\" to field \"{2}\" of type \"{3}\"", this.fieldValue,
                    value.Type, this.fieldName, member.Type));
        }
    }

    private static Dictionary<SelectionComparison, ExpressionType> operationMap =
        new Dictionary<SelectionComparison, ExpressionType>
        {
            { SelectionComparison.Equal, ExpressionType.Equal },
            { SelectionComparison.GreaterThan, ExpressionType.GreaterThan },
        };
}

public enum SelectionComparison
{
    Equal,
    GreaterThan,
    Contains,
};

用法很简单:

var criteria = new SelectionCriteria
{
    selectionComparison = SelectionComparison.GreaterThan,
    fieldName = "worktobegindate",
    fieldValue = DateTime.Now.AddDays(-2)
};

var predicate = criteria .constructPredicate<job>();
var jobs = myDbContext.jobs.Where(predicate);

所以,我的问题 - 我需要一个方法,比如上面的constructSinglePredictate(),它返回一个Expression&gt;并应用.Contains(

将Contains()应用于字符串是很简单的,给定一个字符串来比较它,但是我很难弄清楚如何在表达式中做同样的事情。

想法?

1 个答案:

答案 0 :(得分:0)

像往常一样,我正在思考错误的事情。我不需要在字符串上调用方法的lambda,我需要一个MethodExpression(这里从methodMap字典中提取):

public Expression<Func<T, bool>> constructMethodCallPredicate<T>()
{
    var type = typeof(T);

    if (type.GetProperty(this.fieldName) == null && type.GetField(this.fieldName) == null)
        throw new MissingMemberException(type.Name, this.fieldName);

    MethodInfo method;
    if (!methodMap.TryGetValue(this.selectionComparison, out method))
        throw new ArgumentOutOfRangeException("selectionComparison", this.selectionComparison, "Invalid filter operation");

    var parameter = Expression.Parameter(type);
    var member = Expression.PropertyOrField(parameter, this.fieldName);
    var value = (this.fieldValue == null) ? Expression.Constant(null) : Expression.Constant(this.fieldValue, this.fieldValue.GetType());

    try
    {
        var converted = (value.Type != member.Type)
            ? (Expression)Expression.Convert(value, member.Type)
            : (Expression)value;

        var methodExpression = Expression.Call(member, method, converted);

        var lambda = Expression.Lambda<Func<T, bool>>(methodExpression, parameter);

        return lambda;
    }
    catch (Exception)
    {
        throw new InvalidOperationException(
            String.Format("Cannot convert value \"{0}\" of type \"{1}\" to field \"{2}\" of type \"{3}\"", this.fieldValue,
                value.Type, this.fieldName, member.Type));
    }
}

private static readonly Dictionary<SelectionComparison, MethodInfo> methodMap =
    new Dictionary<SelectionComparison, MethodInfo>
    {
        { SelectionComparison.Contains, typeof(string).GetMethod("Contains", new[] { typeof(string) }) },
        { SelectionComparison.StartsWith, typeof(string).GetMethod("StartsWith", new[] { typeof(string) }) },
        { SelectionComparison.EndsWith, typeof(string).GetMethod("EndsWith", new[] { typeof(string) }) },
    };

public enum SelectionComparison
{
    Equal,
    NotEqual,
    LessThan,
    LessThanOrEqual,
    GreaterThan,
    GreaterThanOrEqual,
    Contains,
    StartsWith,
    EndsWith,
};

获得真实的&#34;喜欢&#34;比较工作,使用SqlFunctions.PatIndex有点复杂,PatIndex()返回一个int,我需要将它包装在一个&gt; 0表达式中,但它也可以正常工作。