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.
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.
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.
Subscribe to be the first to get our expert-written articles and tutorials for developers!