在 Translate 方法中获取 SqlParameterExpression 值
Get SqlParameterExpression value inside Translate method
我正在尝试在 EF Core 5 中实现自定义 IMethodCallTranslator
译者:
public class NpgsqlCustomILikeMethodTranslator : IMethodCallTranslator
{
private readonly MethodInfo _customILikeMethod = typeof(NpgsqlDbFunctionsExtensions)
.GetRuntimeMethod(nameof(NpgsqlDbFunctionsExtensions.CustomILike),
new[] { typeof(DbFunctions), typeof(string), typeof(string) });
public SqlExpression Translate(SqlExpression instance,
MethodInfo method,
IReadOnlyList<SqlExpression> arguments,
IDiagnosticsLogger<DbLoggerCategory.Query> logger)
{
if (method == _customILikeMethod)
{
var pattern = arguments[2];
if (pattern is SqlParameterExpression patternParameter)
{
// Get the value from patternParameter as string
var patternString = ???;
// Do something with patternString
patternString = DoWork(patternString);
// Put changed string as constant
pattern = new SqlConstantExpression(Expression.Constant(patternString), null);
}
return new PostgresILikeExpression(arguments[1], pattern, null, null);
}
return null;
}
}
用法:
var pattern = "%A%";
query = query.Where(u => EF.Functions.CustomILike(u.Name, pattern);
有什么方法可以从 Translate 方法中获取我的模式字符串值“%A%”?
无法在 IMethodCallTranslator
实现中获取 SqlParameterExpression
的值。所以尝试强制 EF Core 为这种方法生成 SqlConstantExpression
。可以通过将 [NotParameterized]
属性添加到所需的函数参数来完成。
public static bool CustomILike(string str, [NotParameterized] string pattern)
我正在尝试在 EF Core 5 中实现自定义 IMethodCallTranslator
译者:
public class NpgsqlCustomILikeMethodTranslator : IMethodCallTranslator
{
private readonly MethodInfo _customILikeMethod = typeof(NpgsqlDbFunctionsExtensions)
.GetRuntimeMethod(nameof(NpgsqlDbFunctionsExtensions.CustomILike),
new[] { typeof(DbFunctions), typeof(string), typeof(string) });
public SqlExpression Translate(SqlExpression instance,
MethodInfo method,
IReadOnlyList<SqlExpression> arguments,
IDiagnosticsLogger<DbLoggerCategory.Query> logger)
{
if (method == _customILikeMethod)
{
var pattern = arguments[2];
if (pattern is SqlParameterExpression patternParameter)
{
// Get the value from patternParameter as string
var patternString = ???;
// Do something with patternString
patternString = DoWork(patternString);
// Put changed string as constant
pattern = new SqlConstantExpression(Expression.Constant(patternString), null);
}
return new PostgresILikeExpression(arguments[1], pattern, null, null);
}
return null;
}
}
用法:
var pattern = "%A%";
query = query.Where(u => EF.Functions.CustomILike(u.Name, pattern);
有什么方法可以从 Translate 方法中获取我的模式字符串值“%A%”?
无法在 IMethodCallTranslator
实现中获取 SqlParameterExpression
的值。所以尝试强制 EF Core 为这种方法生成 SqlConstantExpression
。可以通过将 [NotParameterized]
属性添加到所需的函数参数来完成。
public static bool CustomILike(string str, [NotParameterized] string pattern)