c# - 为 EfCore IQueryable.Where 构建谓词
问题描述
我想Search<T>
为 IQueryable 做一个扩展方法,但是得到一个无法翻译的 LINQ 表达式运行时错误。
public static IQueryable<T> Search<T>(this IQueryable<T> source, Func<T, string> expression, string search)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (string.IsNullOrWhiteSpace(search))
return source;
return source.Where(x => EF.Functions.Like(expression(x), $"%{search}%"));
}
用法:
dbContext.People.Search(x => x.Name, "Joe").ToList();
我猜错误的行是expression(x)
,但正确的方法是什么?
解决方案
它不使用 Like 功能,但作为扩展可以正常工作。
var result = dbContex.Currencies.Search(x=>x.Symbol, "EUR").ToList();
public static IQueryable<T> Search<T>(this IQueryable<T> source, Expression<Func<T,string>> expression, string search)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (string.IsNullOrWhiteSpace(search))
return source;
var method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
var value = Expression.Constant(search, typeof(string));
var exp1 = Expression.Call(expression.Body, method, value);
var ex2 = Expression.Lambda<Func<T, bool>>(exp1, expression.Parameters[0]);
return source.Where(ex2);
}
推荐阅读
- flutter - Flutter 在失败的 PlatformAssetBundle 上崩溃
- twilio - 清除/删除 Twilios SMS 消息队列中的消息
- java - 使用 Jackson 和 Lombok 反序列化 ImmutableList
- asp.net-core - 单选按钮验证不起作用 asp.net core 3.1
- python - Scrapy 跟随链接并提取数据
- html - 将重绘功能从 D3.js v3 迁移到 D3.js v4
- php - 在选择时显示计数而不是重复值 - PHP
- flask - 如何抑制 flask_mail 控制台输出
- android - 如何在非 Android Gradle 项目中创建 Android 库?
- c# - 如何使用应用于文本框(WPF)的样式获取 TextChanged 事件