【问题标题】:How to substitute Expression<Func<T,bool>> into where clause of linq to sql expression如何将 Expression<Func<T,bool>> 替换为 linq to sql 表达式的 where 子句
【发布时间】:2011-04-28 14:46:15
【问题描述】:

我想将以下谓词设置为用表达式语法编写的 linq 语句的 where 子句。

Expression<Func<Purchase, bool>> condition = p => p.Price > 100;

from purchase in dc.GetTable<Purchase>()
where condition
select ...

但是,编译器无法确定使用哪个位置:IQuaryable 或 IEnumerable。 如果不将 linq 表达式转换为方法链,如何解决这个问题?

【问题讨论】:

    标签: c# .net linq linq-to-sql


    【解决方案1】:

    你不能像那样做where condition。要么将条件合并到 where 子句中(where purchase.Price>100),要么在查询表达式中使用 Where(condition) 方法调用,例如

    from purchase in dc.GetTable<Purchase>().Where(condition)
    select ...
    

    这是您可以组合它们的方式。

    【讨论】:

      【解决方案2】:

      试试:

      where condition.Compile()(purchase);
      

      【讨论】:

      • OP 专门说without converting linq expression to method chains
      • 我只想了解表达式语法而不是方法链语法。 (从……哪里……选择)
      • 没有得到那部分,“方法链”,检查我更新的答案。
      • 这一切都很好,直到运行时:),然后它抛出 NotSupportedException Method 'System.Object DynamicInvoke(System.Object[])' has no supported translation to SQL.
      • 正如预期的那样。 ;-) 我不确定你是否真的可以使用这种语法来做到这一点。 .Where(condition) 选项有什么问题?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多