7

I'm wondering how one would translate a sql string to an expression tree. Currently, in Linq to SQL, the expression tree is translated to a sql statement. How does on go the other way? How would you translate

select * from books where bookname like '%The%' and year > 2008 

into an expression tree in c#?

Joo Park
  • 3,115
  • 4
  • 27
  • 31
  • Did you find any solution for this question. I am also in need of getting an expression tree from a sql string in c# – Saravanan Jan 23 '12 at 12:09

2 Answers2

0

I don't know if there's an easier way, but I wrote a lexer and parser for SQL expressions into a custom Abstract Syntax Tree (as I didn't know about .net's Expression Trees at the time) and I didn't really enjoy parsing SQL.

The syntax just is not very parse friendly, as order is different depending on context (e.g. the not in NOT IN vs. IS NOT), tokens are overloaded (the parenthesis for overriding the default operator precedence vs. parentheses for creating a list as in WHERE x IN (1, 2)) and so forth.

Obviously using a parser generator rather than doing your own lexing and parsing would make things easier, but I don't know if there's anything more specific to SQL.

So, writing your own is definitely possible, albeit tedious.

Evgeniy Berezovsky
  • 18,571
  • 13
  • 82
  • 156
0

http://weblogs.asp.net/rajbk/archive/2007/09/18/dynamic-string-based-queries-in-linq.aspx

update

The Entity framework has the Entity SQL language. Not sure if that is what you want though.

http://msdn.microsoft.com/en-us/library/bb738521.aspx

Raj Kaimal
  • 8,304
  • 27
  • 18
  • Well...Sort of. Dynamic Linq allows you to specify your linq lambda expression arguments as strings, but you still have to specify the extension methods (.Select, .Where) of your linq statements directly. – Robert Harvey May 14 '10 at 23:43
  • it would be nice to not use dynamic linq but purely built from System.Linq.Expressions – Joo Park May 14 '10 at 23:53