动态表达EF核心“赞”功能

问题描述 投票:1回答:1

我写了一些代码来制作动态表达式来过滤我的分页。我正在尝试动态表达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:方法提供的参数数量不正确

c# .net-core asp.net-core-2.0 asp.net-core-webapi ef-core-2.0
1个回答
0
投票

如评论中所述,您需要包含EF.Functions作为第一个参数:

var likeMethodCall = Expression.Call(likeMethod, new []
{
    Expression.Property(null, typeof(EF).GetProperty("Functions")),
    memberExpression,
    likeConstant 
});
© www.soinside.com 2019 - 2024. All rights reserved.