[英]How to map Expression<Func<TEntity, bool>> to Expression<Func<TDbEntity, bool>>
[英]Generating an Expression<Func<TEntity, bool>> for multi-level expression
如果在其他答案中有所涉及,请道歉。 我整夜搜索并经历了其他一百个解决方案,但却无法将拼图拼凑在一起。 我已经尝试过LinqPad,PredicateBuilder,ExpressionVisitors等等,但我还在摸不着头脑。
我试图实现比这更复杂的东西,但这段代码显示了问题:
public Expression<Func<TEntity, bool>> GeneratorEqualityTest<TProperty>(Expression<Func<TEntity, TProperty>> accessor, int expectedValue) {
// Help
var argument = Expression.Parameter(typeof(TEntity));
var accessorArgument = Expression.Property(argument, accessor.ToPropertyName());
// Help
Predicate = Expression.Lambda<Func<TEntity, bool>>(Expression.Equal(accessorArgument, Expression.Constant(expectedValue)), argument);
}
当访问器是这样的时,这工作正常: x => x.Value
但不是x => x.Complex.Value
或x => x.Complex.MoreComplex.Value
我正在尝试解析来自> = 5或(5 ... 10)等字符串的表达式,并生成表达式,我可以将其插入到LINQ-to-EF查询的Where子句中(并转换为T-SQL)这对于单级案例工作正常,但我无法弄清楚如何处理表达式。
在EF中,x.Complex.MoreComplex.Value对应于SQL Join。 如果可以将访问者转换为我可以传递给Include()
语句的内容,则可以获得奖励积分
我在Github上放了一个示例项目: https : //github.com/scottt732/ExpressionHelp
由于您正在接收最终值访问器,因此您需要它来应用比较函数(即构建谓词的主体 ):
public Expression<Func<TEntity, bool>> GeneratorEqualityTest<TProperty>(Expression<Func<TEntity, TProperty>> accessor, TProperty expectedValue)
{
var body = Expression.Equal(accessor.Body, Expression.Constant(expectedValue));
var predicate = Expression.Lambda<Func<TEntity, bool>>(body, accessor.Parameters);
return predicate;
}
奖金方式:
static class ExpressionUtils
{
public static IEnumerable<Expression<Func<TEntity, object>>> Includes<TEntity, TProperty>(this Expression<Func<TEntity, TProperty>> accessor)
{
var root = accessor.Parameters[0];
for (var node = accessor.Body as MemberExpression; node != null && node.Expression != root; node = node.Expression as MemberExpression)
yield return Expression.Lambda<Func<TEntity, object>>(node.Expression, root);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.