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 ...

Get Hands-On Full-Stack Web Development with ASP.NET Core now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.