Friday, December 5, 2008

Why LINQ is better than SQL (Part 1?)

To be very honest, LINQ warms the cockles of my heart. The mere fact that I can write a compiler-checked query in C# that references my C# entity class and that query, through some magic incantations, gets executed as a SQL statement against my database...it makes me happy.

But maybe you're more pragmatic than I am. Maybe you think all this LINQ hoo-ha is pure sophistry. Take my word for it, I could go on and on about the wonders of LINQ, but then "I don't have time for this" do I?..Well, maybe one tiny example (since you asked so nicely):

    var r = (
        from e in context.Employee
        where e.Manager.Contact.LastName == "Word"
        select new { e.Contact.FirstName, e.Contact.LastName });

What's the big deal? This query traverses four logical tables. I didn't have to specify how those tables get joined together. Maybe this is kind of obvious, but it surprises me that standard SQL does not have a similar capability. Databases have these things called foreign keys that formalize the relationship between tables. That being the case, why do I have to spell out the relationship between every table in every query.

Don't get me wrong, I love SQL joins. Like the other day, when I needed to identify value gaps in a set of rows. Once upon a time, I probably would've resorted to some process involving cursors, but a simple self-join does the trick. The problem is that the chance to do something "clever" with a join doesn't come up very often. Most of the time (for me, at least), a join is identical to the relationship defined by a foreign key.

3 comments:

PSteele said...

What you're really liking here is the ORM layer (entity framework?) that's providing you the nice query abilities. LINQ is just the cherry on top of that.

iMe said...

are you sure your example works? I tried it and when i hit dot on the table I'm referencing I can pull up the related tables but when I hit dot after that I don't see any column names, just functions relating to LINQ like "add", "addRange", "Aggregate<>", etc... From what I'm experiencing, I will have to do a join anyways, not the magic that you describe in your post. :P

iMe said...

I think I figured it out, you have to start from the highest part in the chain in order to drill down like that.