首页 > 解决方案 > 使用字符串属性名称创建 where x = value lambda 表达式

问题描述

现在我正在做这样的事情:

if (name == "Person")
{
    query = query.Where(o => o.Person == val);
}
else if (name == "Location")
{
    query = query.Where(o => o.Location == val);
}
else if (name == "Date")
{
    query = query.Where(o => o.Date == val);
}
...

我希望能够做这样的事情:

   query = WhereEquals(query, name, val);

标签: c#.net.net-core

解决方案


我对where方法没有答案。但是您可以使用一种扩展方法来实现您的目标。如果您想要完全匹配,此方法使用类似功能,只需 从searchTerm中删除'%' 符号

        public static IQueryable<T> Search<T>(this IQueryable<T> source, string propertyName, string searchTerm)
    {
        if (string.IsNullOrEmpty(propertyName) || string.IsNullOrEmpty(searchTerm))
        {
            return source;
        }

        var property = typeof(T).GetProperty(propertyName);

        if (property is null)
        {
            return source;
        }

        searchTerm = "%" + searchTerm + "%";
        var itemParameter = Parameter(typeof(T), "item");

        var functions = Property(null, typeof(EF).GetProperty(nameof(EF.Functions)));
        var like = typeof(DbFunctionsExtensions).GetMethod(nameof(DbFunctionsExtensions.Like), new Type[] { functions.Type, typeof(string), typeof(string) });

        Expression expressionProperty = Property(itemParameter, property.Name);

        if (property.PropertyType != typeof(string))
        {
            expressionProperty = Call(expressionProperty, typeof(object).GetMethod(nameof(object.ToString), new Type[0]));
        }

        var selector = Call(
                   null,
                   like,
                   functions,
                   expressionProperty,
                  Constant(searchTerm));

        return source.Where(Lambda<Func<T, bool>>(selector, itemParameter));
    }

推荐阅读