Project Only the Names
Easy About 8 min Free, no account needed
Select just the customer names server-side instead of materializing whole entities to read one column.
The brief
You are given an Entity Framework Core ECommerceDbContext over two tables:
Customers(Id,Name,Country)Orders(Id,CustomerId,Total,PlacedAt)
Implement CustomerNames(ECommerceDbContext db, string country) to return the
names of every customer in the given country, as a List<string> ordered
by Name ascending.
You need a single column, but the starter materializes the whole customer
entity, order history included, for every match and then reads just the
Name in memory. It is correct, but on the hidden dataset it drags every
matching customer and all of their orders across the wire when the database
could have returned only the one column you use, so it does vastly more work
than necessary.
Project the Name server-side so the database sends back only that column,
already ordered.
This puzzle runs against a real, throwaway PostgreSQL database created just for your submission and destroyed afterwards.
Starter code
using System.Collections.Generic;
using System.Linq;
using CodeRunner.PuzzleSchemas;
using Microsoft.EntityFrameworkCore;
public class Solution
{
// Materializes the full customer entities (order history and all), then reads
// the Name from each in memory. Correct, but it drags the whole object graph
// across the wire when only Name is used.
public List<string> CustomerNames(ECommerceDbContext db, string country)
{
var customers = db.Customers
.Include(c => c.Orders)
.Where(c => c.Country == country)
.ToList();
return customers
.OrderBy(c => c.Name)
.Select(c => c.Name)
.ToList();
}
}How it is graded
Your LINQ or SQL runs against real PostgreSQL. You see the SQL your code generates on the sample tests and can inspect its execution plan, so you learn when the database did the wrong work.
Related guides
What it practices
- Projections
- Select only the columns and shapes the caller needs instead of materializing whole entities.
Related katas
- One Query, Sixty Thousand Rows Hard Pro Chained collection Includes multiply into a cartesian row explosion. Ask the database for the answer instead of the graph.
- The Order Digest Tree Hard Pro Shape a bounded customer, order, and line-item tree inside one translated EF Core query instead of loading the full graph.
- Existence Without Loading Easy Free Answer a yes/no existence question by asking the database, not by loading the rows to count them.
- Filter Before You Fetch Easy Free Filter measurements on the database, not after loading the whole table.