Using text SQL with LINQ Using text SQL with LINQ sql sql

Using text SQL with LINQ

You can't really do that as expression trees generate SQL from an expression that's built dynamically i.e. from the expressions you can "compile" a SQL, what you're asking is akin to asking for a "SQL-to-LINQ dissasembler".

My suggestion for your problem is - take your SQL queries and save them as views in the database, then map your views in the LINQ-To-SQL .dbml files and add your LINQ queries on top of that.

context.viewSavedFromYourSql.Where(x => x.Name.Contains("Anonymous")).Take(20);

This way LINQ will query from your view, and return only the data you need.

(you can also use table-valued functions instead of views)


Not likely without a significant amount of effort.

What you seem to be asking for is either a sql -> sql model tokeniser or a full blown sql -> IQueryable tokeniser, both which would be significant effort to implement.

My suggestion is either write a rough sql parser to then just put in the required statement, or to rewrite your views as LinqToDatabase queries.

As explanation when you create an IQueryable expression its expression tree is the object logic of the query, your provider then takes that logic and tries to map it into a series of sql statements to execute and a mapper for the results. You seem to be asking for the opposite so you would want to translate a series of sql statements back into an expression tree.

This to me seems like a bit of double work, in that you would map into an expression tree, append onto it, then map back. Not least because a perfect map is probably not possible so you would find that you would get equivalent but not what you expected sql back out.

You may want to take a look at Linker.

It translate SQL statements to LINQ statements. Obviously it can't convert all kind of SQL queries, but it helps you a lot if you want to convert all hard coded SQL queries to LINQ statements.

Sorry if it is not free!