Thursday, June 5, 2008

Piece By Piece Query Building With Linq

In numerous projects in the past, I've found myself needing to write code and build sql queries that filtered results based on one or more criteria and any combination of criteria. I've also needed to write code that returns extra parts of an entity (typically involving the joining of tables, but only under certain conditions.

In this post, I'm assuming that you know at least the very basics about Linq - how to create a DataContext class from a the Linq to SQL designer, select from it's tables and filter the results.

In the past, I have done a few things to solve this type of problem. I would create queries for each scenario, which resulted in a maintenance headache due to the numerous code changes every time a small change was introduced, and of course, more places to mess up. I also tried formulating my stored procedures to return different result sets depending on boolean parameters passed in. This, of course proved to be non-intuitive and error prone due to the variation in the type of data that was coming back. As a result, I felt I always had to choose between a lot of code, or non-intuitive code.

Linq to SQL - Building Queries Piece By Piece

Thanks to expression building capabilities of Linq, we can now build our queries one piece at a time without having to do tricky dynamic sql building while avoiding the caveats of the aforementioned approaches.

An example of a case when you would want to do this sort of thing would be (using an annoying Northwind database example) if you wanted to search for Orders based on any combination of criteria that you allow (e.g. searching by OrderDate, Freight, ShipCountry etc.) and possibly populating the order details of each order.

Traditionally, this would prove to be a bit of a challenge due to the number of queries or complexity of the query you would write to accomplish this, not to mention all of the CRUD code you would have to write. Thanks to Linq, we can now accomplish this in a matter of a handful of lines.

Writing Your Query Piece By Piece

So how is this done? As you create your queries, instead of returning result sets, you are returning an expression tree. An 'expression tree' can be thought of as a query builder in the sql sense. When you are writing your 'select statements' in your code, Linq is storing what it needs to know to query the database when you finally are ready to get the results back.

This means, using the Northwind orders example above, we can just keep defining our Order query piece by piece in a very natural way and we can know that when we are hitting the database, we are getting back exactly what we want.

Here's an example of how you might query Orders in a Northwind database using this 'piece by piece' query approach: