Skip to content
Katabench
Try free

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.

The performance goal

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

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

EF Core practice →

Related guides

What it practices

Projections
Select only the columns and shapes the caller needs instead of materializing whole entities.

Related katas