c# - 使用字符串属性名称创建 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);
解决方案
我对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));
}
推荐阅读
- mysql - 错误 #1046:列的数据太长,但源列和目标列的类型均为 char(1)
- javascript - 工作箱服务人员:无法在模块外使用导入语句
- asp.net-mvc - 我无法通过 EF 将数据添加到 sql 中(非静态方法需要目标)
- python - 从列表中自动加入熊猫数据框
- angular - 资产的角度 SPA 路径无法使用基本 Href 解析
- pdf - itext - 如何在一行文本之前添加一个形状?
- ruby - Ruby:范围还是序列?
- snowflake-cloud-data-platform - Snowflake 数据仓库中的模式版本控制
- java - 独立测试使用 Thymeleaf 的服务
- python - 如何为 Python 做 PHP 的 strtotime 函数