How to convert an expression tree to a partial SQL query?

后端 未结 9 1554
轮回少年
轮回少年 2020-11-29 16:26

When EF or LINQ to SQL runs a query, it:

  1. Builds an expression tree from the code,
  2. Converts the expression tree into an SQL query,
  3. Executes th
9条回答
  •  不知归路
    2020-11-29 17:17

    The short answer seems to be that you cannot use a part of EF or LINQ to SQL as a shortcut to translation. You need at least a subclass of ObjectContext to get at the internal protected QueryProvider property, and that means all the overhead of creating the context, including all the metadata and so on.

    Assuming you are ok with that, to get a partial SQL query, for example, just the WHERE clause you're basically going to need the query provider and call IQueryProvider.CreateQuery() just as LINQ does in its implementation of Queryable.Where. To get a more complete query you can use ObjectQuery.ToTraceString().

    As to where this happens, LINQ provider basics states generally that

    IQueryProvider returns a reference to IQueryable with the constructed expression-tree passed by the LINQ framework, which is used for further calls. In general terms, each query block is converted to a bunch of method calls. For each method call, there are some expressions involved. While creating our provider - in the method IQueryProvider.CreateQuery - we run through the expressions and fill up a filter object, which is used in the IQueryProvider.Execute method to run a query against the data store

    and that

    the query can be executed in two ways, either by implementing the GetEnumerator method (defined in the IEnumerable interface) in the Query class, (which inherits from IQueryable); or it can be executed by the LINQ runtime directly

    Checking EF under the debugger it's the former.

    If you don't want to completely re-invent the wheel and neither EF nor LINQ to SQL are options, perhaps this series of articles would help:

    • How to: LINQ to SQL Translation
    • How to: LINQ to SQL Translation - Part II
    • How to: LINQ to SQL Translation - Part III

    Here are some sources for creating a query provider that probably involve much more heavy lifting on your part to implement what you want:

    • LINQ: Building an IQueryable provider series
    • Creating custom LINQ provider using LinqExtender

提交回复
热议问题