Monday 10 December 2007

Dynamic Queries in LINQ

Dynamic queries are usually used in search screens where the search criteria is optional. This illustrates how to create dynamic queries.

Dynamic Queries

The following code creates a dynamic query:
1.MyDataContext context = new MyDataContext();
2.var query = from customer in context.Customers select customer;
3.var filteredQuery = (from customer in query where customer.ID == newCustomerID select customer).ToList();

This is how it works:
1. Create a new context to query
2. Creates the first part of the query
3. Adds further criteria to the original query, paying attention to the bold part in line 3, where we extend the query variable.

No comments: