c# - 如何将 Expression<Func<TEntity, bool>> 映射到 Expression<Func<TDbEntity, bool>>

标签 c# linq expression func

我怎样才能映射

来自: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/

相关文章:

c - a>b>c 当每个都有数值时进行评估

c# - 使用 GraphDiff 更新多对多关联

c# 对自定义列表进行排序

c# - 获取通用类型的 ICollection 属性

c# - 将 IEnumerables 的 IEnumerable 转换为字典

PHP 预匹配?如何返回不匹配的字符?

C#:从文件名字符串中去除非法字符

c# - 从字符串名称调用方法

c# - ASP :NET MVC multiple words in search

c# - 当 ExecuteScalar 工作正常时,为什么 ExecuteReader 会崩溃读取某些记录的特定数据字段?