With EF Core 10 in an ASP.NET Core API, why can .Select(e => e.ToDto()) read every Employee column while .Select(e => new EmployeeDto(...)) reads only the projected ones?
answer
- an opaque method versus an expression tree
- client evaluation in the top-level projection
- the whole entity is materialized and tracked
- Expression<Func<Employee, EmployeeDto>> for reuse
- ProjectTo<T> or a Mapperly IQueryable method
basics
~20 sEF Core cannot see inside a compiled ToDto method, so it evaluates that final Select on the client: it loads the whole Employee row, Salary included, and tracks it. An inline new EmployeeDto(...) is an expression EF Core translates into a SELECT of just those columns.
solid answer
~50 sEF Core translates the expression tree of a LINQ query. `new EmployeeDto(e.Id, e.FirstName + " " + e.LastName, e.Email, e.Department.Name)` is all expression: it becomes a `SELECT` of four values with a join to departments. `e.ToDto()` is a call to compiled code the provider cannot read. Because it sits in the **top-level projection**, EF Core allows it but evaluates it on the client: it materializes the full `Employee` entity — every mapped column, `Salary` and `BankAccount` included — tracks it unless the query is no-tracking, and only then runs your method. Navigations the method touches, such as `Department`, are not loaded unless you `Include` them, so `e.Department.Name` can throw. Keep `ToDto()` for objects already in memory; for queries use an inline projection, a shared `Expression<Func<Employee, EmployeeDto>>`, or a library projection such as AutoMapper's `ProjectTo<EmployeeDto>` or a Mapperly `IQueryable` method.
code
csharp · 14 linespublic static class EmployeeMappings
{
public static readonly Expression<Func<Employee, EmployeeDto>> AsDto = e =>
new EmployeeDto(e.Id, e.FirstName + " " + e.LastName, e.Email, e.Department.Name);
private static readonly Func<Employee, EmployeeDto> Compiled = AsDto.Compile();
// For entities already in memory (Department must be loaded).
public static EmployeeDto ToDto(this Employee e) => Compiled(e);
}
// Read endpoint: translated to a four-column SELECT with a join.
var staff = await db.Employees.Where(e => e.DepartmentId == deptId)
.Select(EmployeeMappings.AsDto).ToListAsync();go deeper
Remember to put new EmployeeDto(...) inside Select before ToListAsync, so the database returns only the DTO's columns.
Explain expression trees versus compiled methods and EF Core's top-level client evaluation, which loads and tracks whole entities for a ToDto call.
Show how to keep one mapping definition for queries and in-memory objects, verify the SQL in logs, and choose ProjectTo or a Mapperly IQueryable method for many maps.
Decide whether DTO projection is a data-access rule for the codebase, enforced in review or analyzers, rather than a per-endpoint performance tweak.
## Two queries that look the same ```csharp // A: method call in the projection var a = await db.Employees.Where(e => e.DepartmentId == deptId) .Select(e => e.ToDto()).ToListAsync(); // B: constructor in the projection var b = await db.Employees.Where(e => e.DepartmentId == deptId) .Select(e => new EmployeeDto(e.Id, e.FirstName + " " + e.LastName, e.Email, e.Department.Name)) .ToListAsync(); ``` Both return `List<EmployeeDto>` and pass the same unit test against a small database. They do very different work. ## Why EF Core treats them differently EF Core does not run your lambda; it reads the lambda's **expression tree** and translates each node to SQL. In query B every node is translatable: property access, string concatenation, a navigation (`e.Department.Name`, which becomes a join) and a constructor call that EF Core can build from the selected values. The SQL selects four values and nothing else. In query A the projection is a method call, `EmployeeMappings.ToDto(e)`. The provider cannot look inside compiled code. EF Core's rule is that untranslatable expressions are an error anywhere except the **top-level projection** — the last `Select` — where it does **client evaluation**: it fetches whatever data the client-side part needs and runs the method in .NET. What the method needs is the entity `e`, so EF Core: 1. selects **every mapped column** of `Employees`, `Salary`, `BankAccount` and `PerformanceNote` included; 2. materializes full `Employee` instances — and, in a tracking query, **tracks** them, because an entity materialized for client evaluation is tracked; 3. leaves navigations the method reads, such as `Department`, unloaded unless the query has `Include(e => e.Department)` — so `e.Department.Name` inside `ToDto` throws a `NullReferenceException` or needs the include, which fetches yet more columns; 4. finally calls `ToDto` on each instance. The sensitive columns never reach the JSON, because `ToDto` drops them, but they cross the wire from the database, sit in the change tracker for the request, and cost I/O on every call. ## Keeping one mapping definition for both uses The usual compromise is to define the projection once as an expression and derive the in-memory mapper from it: | Need | Tool | Translates to SQL? | |---|---|---| | Read query | `Expression<Func<Employee, EmployeeDto>> AsDto` passed to `Select(AsDto)` | Yes | | Object already loaded (after create) | `employee.ToDto()`, which may call a compiled copy of the expression | Not applicable | | Many projections | AutoMapper `ProjectTo<EmployeeDto>(configuration)` | Yes, it builds the expression from the map | | Many projections, source-generated | Mapperly `public static partial IQueryable<EmployeeDto> ProjectToDto(this IQueryable<Employee> q);` | Yes, the generator emits an expression | Mapperly's documentation notes that queryable projections run as expression trees and so lose some features, such as object factories and deep cloning; AutoMapper's `ProjectTo` likewise only uses map configuration that can become an expression. ## Rules of thumb for an ASP.NET Core read endpoint - **Project in the query.** Return `IQueryable` → `Select(AsDto)` → `ToListAsync()`; never `ToListAsync()` and then map, which loads full entities first. - **No method calls in the final `Select` of a query** unless they take only already-selected scalar values. - **Name the extension method honestly.** `ToDto()` on `Employee` is for in-memory objects; a projection helper lives on `IQueryable<Employee>` or as an expression field. - **Check the SQL.** EF Core logs each command at `Information` under `Microsoft.EntityFrameworkCore.Database.Command`; reading the column list is the fastest way to catch query A in review. - **No-tracking still loads everything.** `AsNoTracking()` removes the tracking cost of query A, not the extra columns. ## Why this matters for an HR portal The goal of the DTO was that salary data does not leave the database for a directory page. Query A meets the letter of that goal — the JSON is clean — while still reading every salary in the department into the web server's memory on every request. Projection is what makes the DTO a data-access boundary as well as a serialization one.
- Does AsNoTracking() make .Select(e => e.ToDto()) acceptable?It removes the change-tracking cost, because the materialized `Employee` instances are no longer tracked, but EF Core still selects every mapped column to build them and still leaves navigations unloaded. The query is cheaper in memory, not in I/O, and sensitive columns still travel from the database.
- Why does EF Core allow the method call in the final Select but throw if the same call appears in Where?Client evaluation is only supported in the top-level projection, where EF Core can fetch rows and post-process them. A method in `Where` would force every row into memory to filter it, so EF Core throws a translation error instead of silently loading the table.
- EF Core inlines the body of an extension method like ToDto into the SQL
- AsNoTracking() makes .Select(e => e.ToDto()) read only the DTO's columns
- Mapping after ToListAsync() is as cheap as projecting inside the query
- Navigations used inside ToDto are loaded automatically by EF Core
- If the JSON has no salary, the salary column was never read