Search code examples
linqormexpression-trees

Who is responsible for transforming LINQ espression tree to a native SQL?


When using an ORM, and writing queries using LINQ, Who is responsible for transforming the LINQ espression tree to a native SQL? is it the ORM itself, or the CLR? or something else?


Solution

  • As Philippe said in comment - the ORM does it. CLR just compiles your LINQ expression as expression tree, and pass this object to IQueryProvider related to the ORM.

    Then this IQueryProvider does parsing of this expression with custom ExpressionVisitor classes. And then based on parsing results - ORM generates pure SQL code, execute it and materialize result.

    Some ORM has optimization for this process. For example Entity Framework saves parsed information in memory into something like SQL Execution Plans, and then just uses it in future queries, so it parses it just once, and then reuse data parsed from an expression tree.

    If expression tree doesn't have linked parameters, then its easy. Otherwise it needs to partially reparse it again for each execution to get used parameter and generate SQL with them.