我怎样才能映射
来自:Expression<Func<TEntity, bool>>
至:Expression<Func<TDbEntity, bool>>
where TEntity: class, new() and TDbEntity: class, new()
TEntity 来自 Domain,TDbEntity 来自 Infrastructure 层,但具有相同的属性。
有可能吗?
最佳答案
对于相对简单的情况(我想在你的情况下表达式很简单)你可以使用 ExpressionVisitor
只有几个覆盖。例如:
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>();
关于c# - 如何将 Expression<Func<TEntity, bool>> 映射到 Expression<Func<TDbEntity, bool>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42902164/