In the spirit of this question, I'd like to know what Gotchas you've come across in Linq. The reason I'm posting this is because I came across a brain teaser today, and I want to share it with the rest of you.
note: I've posted it as an answer
In the spirit of this question, I'd like to know what Gotchas you've come across in Linq. The reason I'm posting this is because I came across a brain teaser today, and I want to share it with the rest of you.
note: I've posted it as an answer
I came across this little subtly today
Dim Activity = (From al In user.ActivityLogs
Take 2
Select al.ActivityDate
Order By ActivityDate Descending)
Although this "works", it calls the "Take" before calling the "Order By", which results in the query returning the "Top 2, Order By Ascending", and then simply reverse orders the two records returned after the fact.
If you want to pull up the last two records in the table, you need to use the following
Dim Activity = (From al In user.ActivityLogs
Select al.ActivityDate
Order By ActivityDate Descending).Take(2)
This will Order the call Descending and then grab the Top 2 records.
For me, it came mostly in the form of LINQ to SQL, where the generated SQL was something completely different than what I thought it was going to be, mostly because of needed parenthesis around certain conditions. Or, certain keywords weren't supported like I expected them too.
Additionally, dealing with the context related to the generated objects was an eye opener when I started initially with LINQ too.
Lastly one developer embedded calculation logic into a LINQ query, and that made it harder to figure out where a calculation went wrong... mostly that's a design issue, but LINQ helped to complicate the process...
The biggest gotcha I came across was the horrible lack of debugger support. Basically, when it works, Linq is nice. But when it doesn't, it is harder to debug than assembly. For instance, I've tried to use it to get data out of an Excel XML file. It worked on my simple testcases, but on some input it just threw a null pointer exception. You have to do a binary search just to find the offending row, and that can take hours.