If it's bad to use inline SQL, how does using LINQ to perform queries differ in practice?

inline, linq, sql

Solution

Ignoring all the non-SQL related uses of LINQ and just considering LINQ-to-SQL.

LINQ queries are objects that retain a query definition and the equivalent SQL is only instantiate at the moment the query is actually iterated. That permits components to be properly separated and allow a pipeline style processing where queries are returned by lower layers (eg. by repositories) and transformed by higher components on the stack. The query can accommodate new filters, joins and other 'artifacts' from each component in the processing pipe, until it reaches the final form that is eventually iterated. This manipulation is impossible in practice using straight text SQL.

Another advantage of LINQ is that its syntax is easier to comprehend for non-database developers. SQL syntax expertise is a surprisingly hard to find asset. Few developers are willing to spend time learning subtler points of SQL beyond `SELECT * FROM ... WHERE ...`. The linq syntax is closer to the .Net everyday environment and leverages the existing skill set at that layer (eg. lambda expressions) as opposed to forcing the developer to learn the proper SQL for the targeted back end (T-SQL, PL-SQL etc). Given that the linq expression expresses the desired result pretty much straight in relational algebra, the providers have a much easier job into generating the appropriate SQL (or even generate straight the execution plan!). Compare this with the impossible task 'generic' database drivers had to face preciously with SQL text. Remember ODBC escape syntax, anyone?

Problem

What's the general consensus on using LINQ to perform queries and manipulation inline and how does this differ to embedding SQL statements into your code (which is considered a no no)?

Original source