views:

262

answers:

4

I have a truckload of xsd with plain SQL queries. I want to migrate to LINQ.

Is there a automated way to generate LINQ equivalents from SQL statements?

+1  A: 

There are no libraries out there that I know of, but it would be possible to do with some work.

I don't think that it would be too hard to parse (a limited but useful sub-set of) sql text into dynamic linq. This probably wouldn't solve 100% of your use cases, but more than likely you could satisy a good 80-90%

Tim Jarvis
+2  A: 

There isn't a simple way to mechanically translate from SQL to LINQ; however, you could re-use your SQL, just using LINQ-to-SQL for the plumbing:

ctx.ExecuteQuery<Foo>(sql, arg1, arg2, ...);

This executes the TQSL from sql, using arg1 and arg2 to replace argument place-holders ({0}, {1} IIRC), and treats the result grid as a sequence of Foo instances (so you don't have to write parsing code).

There is also:

ctx.ExecuteCommand(sql, arg1, arg2, ...);

for when your sql doesn't return a result.

Alternatively, create SPROCs from your SQL and consume those from either LINQ-to-SQL or Entity Framework.

Marc Gravell
+2  A: 

If you just care about getting the results of your LINQ to SQL queries into IEnumberable or similar then you can wrap them in an ExecuteQuery:

var Space = db.ExecuteQuery<Astronaut>("SELECT TOP 10 * FROM dbo.Astronauts");

If you want to actually have proper LINQ queries though then maybe an option, at least a nudge down a possible path, is the LINQ expression tree visualiser that comes with the c# sample. http://blogs.msdn.com/charlie/archive/2008/01/31/expression-tree-basics.aspx

Robert MacLean
A: 

There is a .take(10), or a skip(10).take(10), probably incorrect syntax, but that's how you would do it.