Search This Blog

Friday, January 16, 2009

I love LINQ . It gives the developers the power to query databases and lists in a manner far more succint, readable and elegant than that could otherwise be obtained via traditional looping methods ( you know, the combination kinds of for, if ) that normally result in lines and lines of code, methods and sub-methods calling. LINQ combines the succintness of SQL queries with the compile-time type checking advantage offered by C#, and produces code that is far more intuitive and readable than SQL or C# custom tailored filtering functions.

But after using it for quite sometime, I found that LINQ could be a bit prohibitive. Prohibitive in the sense that you always have to write LINQ expressions that are big, complicated, ugly and undecipherable at times.

Take a look at the below queries, see how much you can understand out of it?

After the grouping, get each of the EnterTime and LeaveTime for each record and put them in a list, and put the list into an ElementInfo object, and so on. If the LeaveTime is a null, then it will find the first record that immediately after the corresponding EnterTime.

With such a long query, debugging it becomes very difficult. I have tried to break it into smaller methods, but so far only succeeded in spinning off one method. The whole query is still can't fit into a page. It's still a pain to read.

If I were to write my own C# code, although I might need more lines to do it, but at least I could write sub-functions to make things easier to understand. But with LINQ... that's the best I could produce, given my limited time and relatively low exposure in it.

With iBATIS you use SQL that can be specified in separate XML-files. Through the iBATIS API you can then make sure your C# code will only receive a collection of structures containing only your EnterTime and LeaveTime values. All information about your tables and group-by clause are isolated in the SQL.

The advantage here is that you use actual SQL, which can easily be debugged with your choice of query-analyser.

IMO iBATIS is clearly better than LINQ when you want to query the database for information but does not care much for the table-structure. In this case you want EnterTime and LeaveTime but you have no interest in letting your C# know about "description and CurrElement tables".

Grouping in any ORM(linq to sql) will probably turn out to be too complex given how an ORM is designed. Did you try to write the query in sql and executing it directly? Maybe it would be simpler. I believe the function to look for is executequery.

Otherwise, i do agree that linq is certainly not a tool for every occasion.