如何使用 EF.Functions 计算 Func<T, bool>?

How to Evaluate Func<T, bool> with use EF.Functions?

我正在尝试在 CSharpScript.EvaluateAsync 中使用 EF.Functions.Like 计算 func<T, bool>,但我在 运行 时出现错误(名称 'EF'在调用 GetPredicate() 方法时不存在于当前上下文中。

创建函数方法:

public static class Helper
{
    public static async Task<Func<T, bool>> GetPredicate<T>(string stringExpression)
            {
                ScriptOptions options = ScriptOptions.Default.AddReferences(references: typeof(T).Assembly);
                Func<T, bool> discountFilterExpression = await CSharpScript.EvaluateAsync<Func<T, bool>>(stringExpression, options);

                return discountFilterExpression;
            }
}

调用方式:

string expString = "x => EF.Functions.Like(x.CodeId, pattern) || EF.Functions.Like(x.Name, pattern) || EF.Functions.Like(x.CategoryId, pattern)";
Func<MyClass, bool> exp = await Helper.GetPredicate<MyClass>(expString);

如何操作?

EF.Functions 通常不应该被评估。

但是要回答您的具体问题,您需要将 reference 添加到 Microsoft.EntityFrameworkCore assemblyimport (using) of Microsoft.EntityFrameworkCore namespace,例如

ScriptOptions options = ScriptOptions.Default
    .AddReferences(references: typeof(T).Assembly)
    .AddReferences(typeof(EF).Assembly) // <--
    .AddImports(typeof(EF).Namespace); // <--