Creating conditional queries with the IQueryable deferred execution

The deferred execution model that IQueryable provides can be very handy when you have an API that can search by using different parameters, where some of them are optional. For example, the GiveNTake application allows users to narrow the search to a specific city and to a specific subcategory, but, if wanted, the user can decide to search in all cities and all categories. Here is how you can build such a dynamic query:

IQueryable<Product> productsQuery = _context.Products
.Include(p => p.Category)
.ThenInclude(c => c.ParentCategory);

if (location != "all")
{
productsQuery = productsQuery.Where(p => p.City.Name == location);
}
if (subcategory != "all")
{
productsQuery = productsQuery.Where(p => p.Category.Name == subcategory)
.Where(p => p.Category.ParentCategory.Name == category);
}
else
{
productsQuery = productsQuery.Where(p =>
p.Category.ParentCategory.Name == category);
}
var products = await productsQuery.ToListAsync();

For now, you can ignore the instances of Include and ThenInclude that were used in the preceding code block—we will talk about them shortly.

The preceding code starts by taking Products DbSet as an IQueryable object—this virtually gives access to the entire products dataset. Then, the code checks if the user specified a certain subcategory and a specific city; if they did, then the code adds another filter (by using the Where operator) to the query. It's important to note that this was all possible due to the fact that the Where operator doesn't change the type of the IQueryable result type (that is, Product). Some operators do change the type of the results, for example, the Select operator allows you to transform the retrieved types. The following code snippet shows an example of how you can retrieve the products titles from your database, without the rest of the product properties:

var products = await productsQuery.Select(p => p.Title).ToListAsync();
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.82.217