如何将LINQ查询的一部分移至可重用的LINQ表达式树 [英] How to move parts of a LINQ query to an reusable LINQ expression tree

查看:56
本文介绍了如何将LINQ查询的一部分移至可重用的LINQ表达式树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过使用表达式树使LINQ查询的某些部分可重用(我想这就是它的调用方式).

I want to make parts of a LINQ query reusable by using expression trees (i think that's how its called).

这是我的查询的简化版本:

Here's a simplified version of my query:

var lQuery = 
  from m in ...
  join a in ... into ta
  from ra in ta.DefaultIfEmpty()
  select 
    new {
      ...
      Status = ra != null ? ... : ..., /* <- i want this to be reusable */
      ...
    };

如您所见,Status的值是通过? :语法确定的,该语法由LINQ自动翻译(我想是一个表达式树,SQL日志最后显示一个CASE WHEN查询).

As you can see, the value of Status is determined via ? : syntax which is translated by LINQ automatically (a expression tree i suppose, the SQL logs show a CASE WHEN query in the end).

如何将代码移至单独的函数,以使我的应用程序在运行时不会引发not supported异常?

How do i move that code to a separate function so that my application does not throw a not supported exception at runtime?

我尝试添加功能

public static System.Linq.Expressions.Expression<System.Func<%type of ra%, %status type%>>
  QueryStatusExpression()
{
  return ra => ra != null ? ... : ...;
}

然后像

Status = QueryStatusExpression().Invoke(ra)

但是会抛出not supported异常.

我现在没主意了.感谢您的帮助.

I'm out of ideas right now. Any help is appreciated.

推荐答案

可以通过combined expressions解决此问题. ="nofollow"> LINQKit 项目.

The issue can be solved via combined expressions of the LINQKit project.

方法如下:

  1. LinqKit引用添加到您的项目中(例如,通过NuGet程序包管理器).

  1. Add the LinqKit reference to your project (e.g. via NuGet package manager).

在.cs文件顶部添加以下行,以作为的扩展方法LINQKit 可用

Add the following line on top of your .cs file to make the extension methods of LINQKit available

using LinqKit; // for System.Linq.Expressions.Expression<>.Invoke()

  • 将表达式定义为静态字段

  • Define the expression as a static field

    public static System.Linq.Expressions.Expression<
      System.Func<%type of ra% ra, %status type%>>
        GetStatusExpression = ra != null ? ... : ...;
    

  • 调用查询中的表达式(请确保将.AsExpandable()添加到第一个表中,如 LINQKit 文档)

    var lQuery = 
      from m in %first table%.AsExpandable() ...
      join a in ... into ta
      from ra in ta.DefaultIfEmpty()
      select 
        new {
          ...
          Status = GetStatusExpression.Invoke(ra),
          ...
        };
    

  • 如果要在普通"代码中使用该表达式,则需要先像

    If you want to use the expression in "normal" code then you need to compile it first like

     public static System.Func<%type of ra% ra, %status type%>
        GetStatusExpressionCompiled = GetStatusExpression.Compile();
    
     ...
    
     if (GetStatusExpressionCompiled(ra) == ...)
     {
       ...
    

    非常感谢速查,它用评论为我指明了正确的方向.

    Big thanks goes to svick for pointing me in the right direction with it's comment.

    这篇关于如何将LINQ查询的一部分移至可重用的LINQ表达式树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆