[英]Convert Expression<Func<T1, bool>> to Expression<Func<T2, bool>>
I am using repository pattern.我正在使用存储库模式。 T1 is the Dto of T2 (ex: UserDto and User)
T1 是 T2 的 Dto(例如:UserDto 和 User)
In the service layer, I pass Expression<Func<UserDto, bool>> as a parameter to a method, which in itself calls a method in the data-access layer in which it passes Expression<Func<User, bool>> .在服务层中,我将Expression<Func<UserDto, bool>>作为参数传递给方法,该方法本身调用数据访问层中的方法,在该方法中传递Expression<Func<User, bool>> 。
Now, you might ask me why don't I just use Expression<Func<User, bool>> all the way but I can't do that.现在,您可能会问我为什么不一直使用Expression<Func<User, bool>>但我不能这样做。 Is it possible to do the conversion of the Expression?
是否可以进行表达式的转换? Note that User and UserDTO have the same props.
请注意,User 和 UserDTO 具有相同的道具。
Yes, as long as you have a method that converts T2 into T1.是的,只要您有将 T2 转换为 T1 的方法。 Here is a simple toy example where T2 is
string
and T1 is int
:这是一个简单的玩具示例,其中 T2 是
string
而 T1 是int
:
// That's the conversion function from T2 to T1
private static int stringToInt(string s) => s.Length;
[TestMethod]
public void Test()
{
// We want to convert this into string->bool
Expression<Func<int, bool>> isEven = i => i % 2 == 0;
MethodInfo stringToIntMethod = ((Func<string, int>) (stringToInt)).Method;
ParameterExpression x = Expression.Parameter(typeof(string));
// That's the converted expression
Expression<Func<string, bool>> converted =
Expression.Lambda<Func<string, bool>>(
Expression.Invoke(isEven,
Expression.Call(null, stringToIntMethod, x)), x);
// Check that it works as expected:
converted.Compile().Invoke("aa").Should().BeTrue();
converted.Compile().Invoke("aaa").Should().BeFalse();
}
If you intend to use the expression with a LINQ provider (eg Entity Framework or Cosmos DB), you must make sure that the entire expression including the conversion call is supported.如果您打算将表达式与 LINQ 提供程序(例如实体框架或 Cosmos DB)一起使用,则必须确保支持包括转换调用在内的整个表达式。 This is usually not the case if it is a method that you defined.
如果它是您定义的方法,则通常不是这种情况。
If that should be problem, can you impose a common interface or base class on both T1 and T2?如果这应该是问题,您可以在 T1 和 T2 上强加一个通用接口或基础 class 吗? In that case you could pass an expression of type
Expression<Func<BaseClass, bool>>
on both layers without conversion.在这种情况下,您可以在两个层上传递
Expression<Func<BaseClass, bool>>
类型的表达式而无需转换。 Failing that (eg if T1 and T2 are completely different) the only way to achieve what you want is to analyze the structure of the expression and build a custom expression converter (eg using ExpressionVisitor
).如果做不到这一点(例如,如果 T1 和 T2 完全不同),实现您想要的唯一方法是分析表达式的结构并构建自定义表达式转换器(例如使用
ExpressionVisitor
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.