With the introduction of LINQ the concept of querying data became a first-class language construct in C# and Visual Basic. LINQ enables to you write type-safe queries which are checked during compile-time. While type-safe queries are fine for certain situations, there might be cases where you want to construct a query on the fly, at runtime, based on certain selections made by the user. This is usually done using a string-based representation of the query. How can this be achieved via LINQ?
The LINQ team at Microsoft provides the Dynamic Query Library which extends the core LINQ API with capability to use string expressions to query data.
To demonstrate the use of Dynamic Query with OpenAccess let us first consider a simple LINQ query against the Northwind database. Following is a LINQ query that retrieves all the ‘Condiments’ with unit price greater than 3, order by the Supplier.
var query = from p in Scope.Extent<Product>()
where p.CategoryID == 2 && p.UnitPrice > 3
Now consider the case where we want to query the database based on user selection i.e. the user selects the category of the product and the unit price. Here is the string based version of the same query, using the Dynamic Query Library.
var query = Scope.Extent<Product>().Where("CategoryID == 2 && UnitPrice > 3").OrderBy("SupplierID");
Note that the where and orderby clauses are now expressed using string expressions. These expressions can be constructed at runtime. Here is the same query using substitution values.
var query = Scope.Extent<Product>().Where("CategoryID == @0 && UnitPrice > @1", 2, 3).OrderBy("SupplierID");
Identifiers of the form @x are used to denote substitution values. The Dynamic Query library provides the capability to translate runtime provided query expressions into lambda expressions.
This is a very basic example demonstrating how to construct LINQ queries on the fly. To be able to use the Dynamic Query Library you need to download the VS 2008 Samples
and include the ‘Dynamic.cs (vb)’ file in your data access project. The file can be found in the ‘\LinqSamples\DynamicQuery’ directory.Included in the same folder is the ‘Dynamic Expressions.html’ that contains documentation for the library.