Review generated dynamic filter

from Expression trees
C# 14 / .NET 10 advanced 6 min 5 issues to find

Review this generated filter builder before exposing it through a public search endpoint.

Build allowlisted equality filters for `IQueryable<T>`, convert text to the exact nullable or non-nullable property type, report unknown input consistently, preserve remote translation, and define bounded cache ownership.

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

generated code is illustrative, not from any one model

Open in playground
Report an error