我写了一些代码来制作动态表达式来过滤我的分页。我正在尝试动态表达EF Core内置函数进行搜索(EF.Functions.Like
)。
我尝试过像bottom这样的方法,但它是一个扩展方法,调用方法时不使用第一个参数。我不知道如何遵循方式==> Ef => Function => Like。
该方法应该像这样使用=> Ef.Functions.Like("Property to search", "%Some Pattern")
var likeMethod = typeof(DbFunctionsExtensions)
.GetMethods()
.Where(p => p.Name == "Like")
.First();
string pattern = $"%{finalConstant}%";
ConstantExpression likeConstant = Expression.Constant(pattern,typeof(string));
// the member expression is the property expression for example p.Name
var likeMethodCall = Expression.Call(method: likeMethod, arguments: new[] { memberExpression, likeConstant });
var searchLambda = Expression.Lambda<Func<T, bool>>(likeMethodCall, parameter);
query = query.Where(searchLambda);
但它抛出了异常的说法
为调用方法'Boolean Like(Microsoft.EntityFrameworkCore.DbFunctions,System.String,System.String)'\ r \ nParameter name:方法提供的参数数量不正确
如评论中所述,您需要包含EF.Functions作为第一个参数:
var likeMethodCall = Expression.Call(likeMethod, new []
{
Expression.Property(null, typeof(EF).GetProperty("Functions")),
memberExpression,
likeConstant
});