比较表达式树中的不同类型

问题描述 投票:0回答:1

在我的API中,我提供了过滤结果的选项-与SQL语句WHERE类似。如果我使用字符串字段并将其与字符串值进行比较,则此方法有效:

https://apiurl/items?filterfieldname=name&filterfieldvalue=test

现在我只取回名称为“ test”的项目

但是,如果我要将其应用于bool字段(在这种情况下,称为“ isActive”),仅返回活动项:

https://apiurl/items?filterfieldname=isActive&filterfieldvalue=true

然后我得到以下异常:System.InvalidOperationException:'未为类型'System.Nullable`1 [System.Boolean]'和'System.String'定义二进制运算符Equal。

我使用以下代码创建表达式:

    static Expression<Func<T, bool>> GetExpressionForFilter<T>(string propertyName, string propertyValue)
    {
        var nameForWhereClause = propertyName.ToLowerInvariant();
        var valueForWhereClause = propertyValue.Trim().ToLowerInvariant();

        var parameterExp = Expression.Parameter(typeof(T), "type");
        var propertyExp = Expression.Property(parameterExp, nameForWhereClause);

        ConstantExpression someValue = Expression.Constant(valueForWhereClause, typeof(string));


        return Expression.Lambda<Func<T, bool>>(Expression.Equal(propertyExp, someValue), parameterExp);
    }

并将表达式应用于我的收藏夹:

        var condition = GetExpressionForFilter<TEntity>(entitiesResourceParameters.FilterFieldName, entitiesResourceParameters.FilterFieldValue);
        condition.Compile();

        var collectionAfterFilter = collectionBeforeFilter.Where(condition).AsQueryable();

我尝试将属性类型转换为字符串,然后将其与“ true”或“ false”字符串进行比较,但这没有什么区别。

我希望能够输入任何类型的字段(包括布尔值)并将其与该字段的值(作为字符串)进行比较(例如,“ true”或“ false”)。这可能吗?

c# rest filter expression-trees
1个回答
0
投票

您可以将字符串值转换为要与之比较的类型。

    var propertyType = property.PropertyType;
    var value = Convert.ChangeType(valueForWhereClause, propertyType);

    ConstantExpression someValue = Expression.Constant(value, propertyType);
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.