IQueryable<T> represents a sequence that callers can query before retrieving its objects. It extends IEnumerable<T>. In an Entity Framework Core repository, exposing IQueryable<Product> lets callers use LINQ to request the products they need without knowing how the repository stores them. section 7.2.5
Listing 7.18 The contents of the IStoreRepository.cs file in the SportsStore/Models folder
namespace SportsStore.Models {
public interface IStoreRepository {
IQueryable<Product> Products { get; }
}
}
The repository contract exposes Products as IQueryable<Product>, leaving query composition to its callers. section 7.2.5
Listing 7.19 The contents of the EFStoreRepository.cs file in the SportsStore/Models folder
namespace SportsStore.Models {
public class EFStoreRepository : IStoreRepository {
private StoreDbContext context;
public EFStoreRepository(StoreDbContext ctx) {
context = ctx;
}
public IQueryable<Product> Products => context.Products;
}
}
The Entity Framework Core implementation supplies that property directly from StoreDbContext. section 7.2.5
Choose when the query should run:
- Add LINQ operations to an IQueryable<T> before evaluating it to have the database retrieve the requested data, rather than retrieving everything and discarding unwanted objects. section 7.2.5 section 36.3.2
- Do not repeatedly enumerate the same query by accident: each enumeration evaluates it again and sends another database query. section 7.2.5
- When repeated reads need the same results, retain the retrieved list. Operations on those existing results do not require another database query. section 36.3.2
Sorting in a Blazor component
At /forms, applying OrderBy to an IQueryable<T> and then calling ToListAsync sends a new query; applying OrderBy to the existing result data sorts without one. Click the Sort buttons and check the ASP.NET Core server log to see the difference. section 36.3.2



