【发布时间】:2019-11-26 06:36:07
【问题描述】:
我有两种表达方式:
Expression<Func<T1, T2>>
Expression<Func<T2, bool>>
我想将这些组合起来,得到一个 Expression
我在 Expression.Invoke() 的帮助下将它们组合起来,但它不起作用。
//Extensinon method
public static Expression<Func<T1, bool>> Compose<T1, T2>(this Expression<Func<T1, T2>> convertExpr, Expression<Func<T2, bool>> predicate)
=> Expression.Lambda<Func<T1, bool>>(Expression.Invoke(predicate, convertExpr.Body), convertExpr.Parameters.First());
...
Expression<Func<One, Two>> convert;
Expression<Func<Two, bool>> predicate;
Expression<Func<One, bool>> filter=convert.Compose(predicate);
// Works fine
List<One> lst;
lst.AsQueryable().Where(filter);
DbSet<One> src;
// In next line throws runtime NotSupportedException: The LINQ expression node type 'Invoke' is not supported in LINQ to Entities
src.Where(filter);
更新
例如:
public class Book
{
public int Id {get; protected set;}
public string Name {get; protected set;}
public virtual Genre {get; protected set;}
}
public class Genre
{
public int Id {get; protected set;}
public string Name {get; protected set;}
}
...
Expression<Func<Book, Genre>> convert = b=>b.Genre;
Expression<Func<Genre, bool>> predicate = g=>g.Name=="fantasy";
// Need: b=>b.Genre=="fantasy"
Expression<Func<Genre, bool>> filter=convert.Compose(predicate);
// Works fine
List<Book> lst;
lst.AsQueryable().Where(filter);
DbSet<Book> books;
// In next line throws runtime NotSupportedException: The LINQ expression node type 'Invoke' is not supported in LINQ to Entities
books.Where(filter);
【问题讨论】:
-
您是否得到错误或错误的结果?请描述你的输出。
-
我收到运行时错误:System.NotSupportedException:LINQ to Entities 不支持 LINQ 表达式节点类型“Invoke”
-
我对类似问题的评论:我在完全外连接代码中遇到了类似的问题 - 它为完全外连接构建表达式树,在 LINQ to SQL 中运行良好,但不适用于 EF。我构建了一个
ExpressionVisitor,它本质上是LINQKit 的Invoke/Expand的有限版本,称为Apply,它就地扩展了LambdaExpression,你可以看到here。请注意,当null是一个参数时,这个特定的Apply对null传播有特殊的考虑(静态处理null.member->null,就好像它是null?.member)。
标签: c# entity-framework linq lambda expression