View By Category

Query Abstraction with LINQ

So recently I was playing with an abstraction for dynamic LINQ queries. The typical usage scenario arises when one needs to search one or more tables with “dynamic” filter patterns. Usually this is one of those intoxicating multiple search criteria (“Advanced Search”) screens.

To illustrate my point, let’s work with this basic schema, below:

So there is nothing fancy in the design here. We’re going to have the opportunity to query these two tables in a number of ways, as a short example, with any combination of the following:

After converting this to a model we can query using LINQ (by using the ADO.Net Entity Framework or LINQ to SQL as an example), we can expose the model for querying, in the fashion (note: I’m using LINQ to SQL for this example):

However, it’s a rare day when such an approach is all that maintainable – not to mention, it’s likely you could have a number of different combinations of filter clauses. Introducing Query Abstraction!

Let’s create a class and call it CustomerQuery. The constructor shall take an argument – the DataContext. In the constructor we will construct a “base” query which will be the basis for all queries – you can choose to make this query as basic or restricted as common sense allows the shortest query would be something like “SELECT * FROM Customers” – note the equivalent in the example below.

Now specifying multiple search parameters is incredibly easy, and you can hide some of the query implementation away from the calling code. Very useful for removing some ugly UI-based logic from your code (like only adding where clauses based on filtering “not selected” magic numbers and the like.

Leave a comment if this helped you

About Rob Sanders

IT Professional and TOGAF 9 certified architect with nearly two decades of industry experience, 18 years in commercial software development and 11 years in IT consulting. Check out the
"About Rob" page for more information.

Post navigation

Stuff to cover the hosting costs

Disclaimer

Privacy: Ads are generated on this site. Google may collect cookies about your interests to make ads more relevant. To Opt out or find more information, see this blog or also see the Google Privacy Center