本文介绍了如何映射表达式< Func< TEntity,bool>>>到表达< Func< TDbEntity,bool>>>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何映射
:表达式< Func< TEntity,bool>>
到:表达< Func< TDbEntity,bool>>
where TEntity: class, new() and TDbEntity: class, new()
TEntity来自Domain和TDbEntity来自于基础架构层,但具有相同的属性。
TEntity is from Domain and TDbEntity is from Infrastructure layer, but have same properties.
可以吗?
推荐答案
对于相对简单的情况(我猜你的表达式很简单)可以使用 ExpressionVisitor
,只需要几个覆盖。例如:
For relatively simple cases (and I guess in your case expressions are simple) you can use ExpressionVisitor
with only a couple of overrides. For example:
public static class ExpressionExtensions {
public static Expression<Func<TTo, bool>> ReplaceParameter<TFrom, TTo>(this Expression<Func<TFrom, bool>> target) {
return (Expression<Func<TTo, bool>>) new WhereReplacerVisitor<TFrom, TTo>().Visit(target);
}
private class WhereReplacerVisitor<TFrom, TTo> : ExpressionVisitor {
private readonly ParameterExpression _parameter = Expression.Parameter(typeof(TTo), "c");
protected override Expression VisitLambda<T>(Expression<T> node) {
// replace parameter here
return Expression.Lambda(Visit(node.Body), _parameter);
}
protected override Expression VisitMember(MemberExpression node) {
// replace parameter member access with new type
if (node.Member.DeclaringType == typeof(TFrom) && node.Expression is ParameterExpression) {
return Expression.PropertyOrField(_parameter, node.Member.Name);
}
return base.VisitMember(node);
}
}
}
用法是:
Expression<Func<ErrorModel, bool>> where = (c) => c.Created <= DateTime.UtcNow && c.ErrorCode == "code";
var replaced = where.ReplaceParameter<ErrorModel, Error>();
这篇关于如何映射表达式< Func< TEntity,bool>>>到表达< Func< TDbEntity,bool>>>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!