Search code examples
linqlinq-to-sqlexpression-trees

Convert SQL Query back to Linq Expression programmatically


Is it possible to somehow programmatically convert a sql query to a linq expression tree? The sql query is supposed to be generated by this linq query, so I'm thinking of it as a poor man's serialization\deserialization of linq queries to t-sql format.

Thank you.


Solution

  • Everything is possible, it just requires a truckload of work. The problem is that you first have to parse the SQL query, and interpret the AST to convert it into a linq expression tree. This isn't trivial, as Linq isn't 1:1 compatible with sql: for example, in linq, aggregates on a groupby are external to the groupby, while in SQL they're internal: they have to be in the same scope as the groupby otherwise they won't work. This kind of info is needed for converting linq queries into SQL queries but also the other way around.

    So to store queries, I'd chose a different route, e.g. a specification pattern