审查生成的动态筛选器

来自 表达式树
C# 14 / .NET 10 高级 6分钟 找出 5处问题

在这个生成的筛选器构建器用于公开搜索接口前,对它进行审查。

为 `IQueryable<T>` 构建有白名单的等值筛选;把文本转换成准确的可空或非可空属性类型;统一报告未知输入;保留远程翻译,并定义有界缓存所有权。

csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

public static class DynamicFilter
{
    public static Expression<Func<T, bool>> Build<T>(string propertyName, string rawValue)
    {
        var parameter = Expression.Parameter(typeof(T), "item");
        var property = Expression.Property(parameter, propertyName);
        var constant = Expression.Constant(rawValue);
        var comparison = Expression.Equal(property, constant);
        return Expression.Lambda<Func<T, bool>>(comparison, parameter);
    }

    public static IEnumerable<T> Apply<T>(IQueryable<T> source, string propertyName, string rawValue)
    {
        var predicate = Build<T>(propertyName, rawValue);
        return source.AsEnumerable().Where(predicate.Compile());
    }

    public static string CacheKey<T>(Expression<Func<T, bool>> predicate)
        => predicate.ToString();
}

生成代码仅作示例,不代表任何特定模型

在试验场中打开
报告错误