Do you only get the rows you need?

Last updated by Jernej Kavka (JK) [SSW] 11 months ago.See history

It's expensive retrieving data from a database, as such it's important to only ask for the rows you require when getting data.

Entity Framework nicely translates the various filters like the Where method into SQL WHERE clauses. This makes it really easy to write nice readable code that is also very efficient.

List<Sale> sales = context.Sales.ToList();
foreach (var sale in sales)
{
    if (sale.ProductId == request.ProductId)
    {
        // Do stuff
    }
}

Bad example - Retrieved all the data instead of items that matched the product id.

List<Sale> sales = context.Sales
      .Where(sale => sale.ProductId == Request.ProductId)
      .ToList();
      
foreach (var sale in sales)
{
    // Do stuff
}

Good example - Only the data required was retrieved from the database

We open source. Powered by GitHub