📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How should you map between EF Core entities and DTOs in .NET 10? Compare hand-written mapping, AutoMapper and Mapperly (a source generator), including their current licences, run-time cost and failure modes, and explain why projecting with Select (or ProjectTo) in the query often beats mapping entities after loading them.

Mapper pattern in .NET 10: hand-written mapping (extension methods, constructors), AutoMapper (reflection/expression-compiled, ProjectTo, AssertConfigurationIsValid; dual RPL-1.5/commercial from v15, July 2025; free Community edition under US$5M revenue; 14.x last MIT with an unpatched advisory), Mapperly (Apache 2.0 source generator, build-time diagnostics, IQueryable projections), mapping after loading vs Select projection in EF Core (over-fetching, tracking, lazy-loading N+1), and testing mappings.

Mid-Level Theory Intermediate automapper design-patterns dto ef-core mapper mapperly

🎯 Key points

  • Mapper pattern: a separate object/function that moves data between two models so neither knows about the other
  • Hand-written mapping: explicit, debuggable, compile-time checked; costs typing and can silently miss a new property
  • AutoMapper: convention-based run-time mapping; ProjectTo builds expression trees for EF Core; always run AssertConfigurationIsValid in a test, or unmapped destination members silently stay default
  • AutoMapper licence (Nov 2026): v15.0 (2 July 2025) onwards, current line 16.x, is dual RPL-1.5/commercial under Lucky Penny Software, free Community edition under US$5M gross annual revenue; 14.x and earlier stay MIT but 14.x has a DoS advisory (GHSA-rvv3-g6hj-g44x) patched only in commercial versions
  • Mapperly: Apache 2.0 source generator; generates plain C# at build time, so near hand-written speed, no reflection, trimming/Native AOT safe; unmapped members reported as RMG012/RMG020 warnings you can raise to errors
  • Mapperly can generate IQueryable<T> projection methods that EF Core translates to SQL
  • Projecting with Select/ProjectTo fetches only needed columns, skips change tracking and avoids lazy-loading N+1; mapping loaded entities over-fetches
  • Keep mapping logic dumb: no business rules, no database calls, no service lookups in mapping profiles

⏱ 30-second answer

The Mapper pattern keeps two models (entity and DTO) apart by putting the conversion in one place. In .NET 10 there are three common options:

  • Hand-written mapping (extension methods or constructors): explicit, fast, compile-checked. The risk is forgetting a new property.
  • AutoMapper: convention-based run-time mapping with ProjectTo. Since v15.0 (July 2025) it's dual-licensed RPL-1.5/commercial (Lucky Penny Software), free for companies under US$5M revenue.
  • Mapperly: an Apache 2.0 source generator. It writes the mapping code at build time, reports unmapped members as diagnostics, is AOT-safe and can generate IQueryable projections.

The bigger win is often where you map. Projecting with Select in the query fetches only the needed columns, skips tracking and avoids lazy-loading N+1. Loading entities and mapping them afterwards over-fetches. The trade-off is convenience against explicitness, licence cost and run-time surprises.

🗣 Full answer (senior)

How I would answer this in an interview

"Mapping is the Mapper pattern: one place that knows both models, so the entity doesn't know about the DTO and the DTO doesn't know about the entity. In .NET I see three ways to do it.

Hand-written mapping is a static extension method like order.ToDto(), or a DTO constructor. It's explicit, you can step through it, and renaming a property breaks the build. The weakness is that adding a property to both sides compiles fine even if you forget to map it. AutoMapper is convention-based: you configure profiles, and it builds and compiles mapping plans at run time. It's convenient for large, flat models, and ProjectTo<T>() turns a mapping into an expression tree EF Core can translate. But errors are run-time errors: an unmapped destination member silently stays default unless you call AssertConfigurationIsValid in a test, and complex profiles with ForMember and resolvers hide logic where nobody looks. The licence changed too: from v15.0 in July 2025, AutoMapper is dual-licensed under RPL-1.5 or a commercial licence from Lucky Penny Software, with a free Community edition for companies under US$5 million gross revenue. Versions 14.x and earlier stay MIT, but 14.x has a published DoS advisory that's only patched in the commercial versions. Mapperly is the option I default to now: it's Apache 2.0 and a source generator, so you declare partial methods on a [Mapper] class and it writes plain C# at build time. There's no reflection, so it works with trimming and Native AOT, runs at hand-written speed, and unmapped members show up as build warnings you can make errors. It can also generate an IQueryable<Order> to IQueryable<OrderDto> projection.

The mistake I see matters more than the library choice: loading full entities, often with Includes or lazy loading, and then mapping them. For example, at [company] we [had an order-list endpoint that loaded orders and mapped them with AutoMapper], and [lazy loading fired [n] extra queries per page]. I [replaced it with a projection to the DTO in the query], and [p95 dropped from [x] ms to [y] ms]. Whatever tool you use, map in the query when you're reading, and keep mappings free of business logic."


Comparison (as of November 2026)

Hand-written AutoMapper 16.x Mapperly 4.x
Licence None Dual RPL-1.5 / commercial (from v15.0, Jul 2025); Community edition free < US$5M revenue Apache 2.0
How it works Your code Run-time configuration, compiled expression plans Source generator at build time
Unmapped member Silent (unless tested) Silent unless AssertConfigurationIsValid Build diagnostic (configurable to error)
Debuggable Yes Hard (generated plans) Yes (generated .g.cs)
EF Core projection Select(...) ProjectTo<T>(config) Generated IQueryable method
Native AOT / trimming Yes Problematic (reflection) Yes
Run-time cost Lowest Startup config + per-map overhead Same as hand-written

Map after loading vs project in the query

Load entities, then map Project with Select/ProjectTo
Columns fetched All, plus Includes Only those in the DTO
Change tracking Yes, unless AsNoTracking None (non-entity result)
Lazy loading Can trigger N+1 during mapping Navigations become SQL joins
Memory Full entity graph Just the DTOs
When it's right Write side: you load to change Read side: screens, lists, reports

Production example

An order history endpoint loaded 50 orders with lines and customer, then mapped them with AutoMapper; with lazy loading on, mapping triggered about 100 extra queries per page and p95 was around 900 ms. A Mapperly-generated IQueryable projection produced one SQL query with three joins, p95 dropped to about 70 ms and allocations per request fell by roughly 85%.

🔍 What the interviewer is checking

Checks whether the candidate can compare mapping approaches on correctness, cost and licensing, and knows that projecting in the query matters more than the library.

Green flags

  • Knows AutoMapper's licence change (v15, RPL-1.5/commercial, Community edition) and Mapperly's Apache 2.0 licence.
  • Explains source generation vs run-time reflection, including AOT.
  • Mentions AssertConfigurationIsValid or build diagnostics for unmapped members.
  • Projects with Select/ProjectTo on reads.
  • Keeps business logic out of mappings.

Red flags

  • "Always use AutoMapper" with no awareness of licensing or failure modes.
  • Loads entities and maps them for every read.
  • Puts database calls in resolvers.
  • Doesn't know what a source generator is.

📚 Learn in depth

1. The Mapper pattern

Fowler's PoEAA describes a Mapper as an object that sets up communication between two independent objects so that neither knows about the other. Data Mapper (what EF Core is) is the persistence-specific version; entity-to-DTO mapping is the same idea at the API boundary.

   Order (entity)                         OrderDto (contract)
        \                                     /
         \----->   OrderMapper   <-----------/
                (only place that knows both)

2. Hand-written mapping

Static extension methods (ToDto), DTO constructors or static factory methods. The compiler checks every assignment, and you can debug it. To catch forgotten properties, write a test that fills every source property and asserts every destination property is non-default, or use positional records so a new DTO parameter forces a compile error at each construction site.

For EF Core projections, write the mapping as an Expression<Func<Order, OrderDto>> (a static field) so it can be used in Select and compiled for in-memory use.

3. AutoMapper internals and costs

  • Configuration scans profiles at start-up and builds an execution plan per type map as an expression tree, compiled lazily on first use.
  • Map executes the compiled plan: fast after warm-up, but with overhead for type-map lookup, and the first call pays compilation.
  • ProjectTo<T> builds a Select expression from the configuration for LINQ providers; resolvers that run C# code can't be translated.
  • AssertConfigurationIsValid() checks every destination member is mapped; without it, misses are silent.

Licensing (checked November 2026): Jimmy Bogard moved AutoMapper and MediatR to Lucky Penny Software, and from AutoMapper 15.0 (2 July 2025) new versions are dual-licensed under the Reciprocal Public License 1.5 or a paid commercial licence. RPL-1.5 is a reciprocal (copyleft-style) licence, so closed-source commercial use effectively requires the commercial licence. A free Community edition covers companies and individuals under US$5 million gross annual revenue. The commercial licence key is set with cfg.LicenseKey or the AUTOMAPPER_LICENSE_KEY/LUCKYPENNY_LICENSE_KEY environment variables. Versions up to 14.x remain MIT, but 14.x carries a denial-of-service advisory (GHSA-rvv3-g6hj-g44x) that is fixed only in the commercial line. The current line is 16.x.

4. Mapperly internals

Mapperly (Riok.Mapperly, Apache 2.0, 4.3.1 stable with 5.0 in preview) is an incremental Roslyn source generator. You declare a partial class with [Mapper] and partial methods; at build time it emits the method bodies as ordinary C# into obj/.../generated. Consequences:

  • No reflection or run-time configuration, so no start-up cost and it's trimming and Native AOT compatible.
  • Unmapped source or target members produce diagnostics (raise them to errors in .editorconfig to fail the build).
  • Attributes like [MapProperty], [MapperIgnoreTarget] handle exceptions to the convention.
  • A partial method returning IQueryable<TTarget> from IQueryable<TSource> generates a Select expression that EF Core translates.

5. Projection vs mapping loaded entities

Loading tracked entities and mapping them: EF materialises every column, builds the change-tracker snapshot, fixes up navigations, and lazy loading (if enabled) fires a query each time the mapper touches an unloaded navigation. A projection to a non-entity type is translated into a SELECT of only the needed columns, with joins for navigations, and isn't tracked.

Rule of thumb: write side loads entities because you're about to change them; read side projects.

6. Keep mapping dumb

Mapping profiles that call services, read the database or compute business values hide logic in a place nobody reviews or tests. If a value needs a rule, compute it in the domain or the query and map the result.

Try it yourself

  1. Write the same entity-to-DTO mapping by hand, with AutoMapper and with Mapperly; benchmark 1 million maps with BenchmarkDotNet ([MemoryDiagnoser]).
  2. Add a property to both entity and DTO without mapping it; see which approach tells you.
  3. Open Mapperly's generated file and read the code.
  4. Compare SQL for ToListAsync() then map vs a projection, with LogTo(Console.WriteLine).
  5. Turn on lazy loading, map a list of entities, and count queries with an interceptor or SQL logs.
  6. Publish a small app with Native AOT using each mapper and read the trimming warnings.

💻 Code

The same mapping three ways, plus a projection that EF Core translates to SQL.

namespace Shop.Contracts;

public sealed record OrderLineDto(string Sku, int Quantity, decimal UnitPrice);
public sealed record OrderDto(Guid Id, string CustomerName, string Status, IReadOnlyList<OrderLineDto> Lines);
public sealed record OrderSummaryDto(Guid Id, string CustomerName, int LineCount, decimal Total);
namespace Shop.Mapping;

using System.Linq.Expressions;
using Shop.Contracts;
using Shop.Domain;

// 1. Hand-written: explicit and compile-checked; the expression form works in EF Core queries too
public static class OrderMappings
{
    public static OrderDto ToDto(this Order order) => new(
        order.Id,
        order.Customer.Name,
        order.Status.ToString(),
        [.. order.Lines.Select(l => new OrderLineDto(l.Sku, l.Quantity, l.UnitPrice))]);

    public static readonly Expression<Func<Order, OrderSummaryDto>> ToSummary = o => new OrderSummaryDto(
        o.Id, o.Customer.Name, o.Lines.Count, o.Lines.Sum(l => l.Quantity * l.UnitPrice));
}
namespace Shop.Mapping;

using Riok.Mapperly.Abstractions;
using Shop.Contracts;
using Shop.Domain;

// 2. Mapperly: code generated at build time; unmapped members become build diagnostics
[Mapper]
public static partial class OrderMapper
{
    [MapProperty(nameof(Order.Customer) + "." + nameof(Customer.Name), nameof(OrderDto.CustomerName))]
    public static partial OrderDto ToDto(this Order order);

    public static partial OrderLineDto ToDto(this OrderLine line);

    // Generates a Select expression that EF Core translates to SQL
    [MapProperty(nameof(Order.Customer) + "." + nameof(Customer.Name), nameof(OrderDto.CustomerName))]
    public static partial IQueryable<OrderDto> ProjectToDto(this IQueryable<Order> query);
}

// 3. AutoMapper (v15+ needs a licence key unless you qualify for the Community edition):
// builder.Services.AddAutoMapper(cfg =>
// {
//     cfg.LicenseKey = builder.Configuration["AutoMapper:LicenseKey"];
//     cfg.CreateMap<Order, OrderDto>().ForMember(d => d.CustomerName, o => o.MapFrom(s => s.Customer.Name));
//     cfg.CreateMap<OrderLine, OrderLineDto>();
// });
// Test: new MapperConfiguration(...).AssertConfigurationIsValid();   // otherwise unmapped members are silent
namespace Shop.Queries;

using Microsoft.EntityFrameworkCore;
using Shop.Contracts;
using Shop.Mapping;

public sealed class OrderQueries(ShopDbContext db)
{
    // Read side: project in the query. One SELECT with only the needed columns, no tracking, no N+1.
    public Task<List<OrderDto>> RecentForCustomerAsync(Guid customerId, CancellationToken ct) =>
        db.Orders
          .Where(o => o.CustomerId == customerId)
          .OrderByDescending(o => o.CreatedAt)
          .Take(20)
          .ProjectToDto()
          .ToListAsync(ct);

    public Task<List<OrderSummaryDto>> SummariesAsync(CancellationToken ct) =>
        db.Orders.Select(OrderMappings.ToSummary).ToListAsync(ct);

    // Anti-pattern: loads every column of orders, lines and customers, tracks them, then maps in memory
    // var orders = await db.Orders.Include(o => o.Lines).Include(o => o.Customer).ToListAsync(ct);
    // return orders.Select(o => o.ToDto()).ToList();
}
# .editorconfig: make Mapperly's unmapped-member warnings fail the build
[*.cs]
dotnet_diagnostic.RMG012.severity = error   # target member has no source
dotnet_diagnostic.RMG020.severity = error   # source member not mapped to any target

⚠ Common mistakes

  • Mistake: Loading full entities (with Include or lazy loading) and mapping them for read endpoints. Why it is wrong: It over-fetches columns, tracks entities and can fire N+1 queries during mapping. Instead: Project to the DTO in the query with Select, ProjectTo or a Mapperly IQueryable method.
  • Mistake: Using AutoMapper without AssertConfigurationIsValid in a test. Why it is wrong: Unmapped destination members silently stay default. Instead: Run the assertion in a unit test, or use a generator that reports at build time.
  • Mistake: Upgrading AutoMapper past 14.x without checking the licence. Why it is wrong: v15+ is RPL-1.5/commercial; closed-source use above the Community threshold needs a paid licence. Instead: Check eligibility, buy a licence, or migrate to Mapperly or hand-written mapping.
  • Mistake: Staying on AutoMapper 14.x indefinitely to avoid the licence. Why it is wrong: 14.x has a published DoS advisory with no patch in the free line. Instead: Plan a migration or license a patched version.
  • Mistake: Putting business logic or database calls in mapping profiles or custom resolvers. Why it is wrong: It hides rules in configuration, and resolvers can't be translated by ProjectTo. Instead: Compute values in the domain or query; keep mapping dumb.
  • Mistake: Using a reflection-based mapper in a Native AOT or trimmed app. Why it is wrong: Trimming can remove members it needs, causing run-time failures. Instead: Use Mapperly or hand-written mapping.
  • Mistake: Hand-writing mappings with no test for new properties. Why it is wrong: A property added to both sides compiles even if unmapped. Instead: Use positional records or a reflection-based completeness test.

🏛 Senior insight: trade-offs

I treat mapping as a boring, explicit concern: for new .NET 10 services I default to Mapperly or hand-written mappings, both compile-time checked and free. The more important decision is to project on the read side, which usually has a bigger performance effect than the choice of library.

Option When it fits Cost When not to
Hand-written Small/medium models, AOT, maximum clarity Typing; silent misses without tests Hundreds of flat types
Mapperly Most new services; AOT; projections Build-time generator, attribute config for exceptions Heavily dynamic mappings
AutoMapper (licensed) Existing large codebases already invested Licence (above Community threshold), run-time errors, reflection New AOT services; teams avoiding RPL/commercial terms
Projection in query Every read endpoint Mapping must be translatable Write side (you need the entity)

I'd measure with BenchmarkDotNet for the mapper itself, but mostly with SQL logs and Application Insights dependency counts per request, because the expensive mistakes are in the queries, not the mapping code.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says projecting in the query fetches only needed columns Why: Checks how LINQ to Entities translates projections to SQL
    How to answer

    In EF Core, DbSet<T> is an IQueryable<T>, so Where, Select and so on build an expression tree, and EF Core translates it to SQL when you enumerate, caching the translation by query shape. Only what EF understands translates, like properties, operators and many string, date and EF.Functions methods. Since EF Core 3.0, client evaluation is allowed only in the final Select, so anything else untranslatable throws. For reads I use AsNoTracking or projections, AsSplitQuery when collection includes explode, and I check the SQL with ToQueryString(), logging and Query Store.

  2. When: Candidate mentions ProjectTo or a generated IQueryable projection Why: Checks expression trees behind ProjectTo and IQueryable projections
    How to answer

    An expression tree is code represented as data. If you assign a lambda to Expression<Func<Order,bool>>, the compiler builds an object tree of parameter, member, binary and constant nodes instead of IL, and that is what lets EF Core read your Where and turn it into SQL. You can build trees with the Expression factory methods, rewrite them with ExpressionVisitor, and turn them into delegates with Compile(). Compiling is expensive, so cache the result, and under Native AOT it falls back to a slower interpreter. Only expression-bodied lambdas qualify, and features like ?., tuple literals and switch expressions are not allowed.

  3. When: Candidate mentions AutoMapper's licence change Why: Checks awareness of the same Lucky Penny licence change for MediatR
    How to answer

    The GoF Mediator stops objects talking to each other directly: colleagues send messages to a mediator, which turns many-to-many coupling into many-to-one (a dialog coordinating its controls).

    MediatR is really an in-process request dispatcher: Send(IRequest<T>) goes to exactly one handler, Publish(INotification) to many, and IPipelineBehavior wraps every handler with validation, logging or transactions.

    It's indirection for nothing when an endpoint just sends to a handler that calls a repository: injecting the handler gives the same decoupling, and "go to definition" still works.

    Licensing: since v13 (July 2025) MediatR is dual RPL-1.5 / commercial under Lucky Penny Software, free (Community edition) under US$5M revenue; 12.5.0 is the last Apache 2.0 version.

    Alternatives: direct handler injection with decorators, or a source-generated mediator. The trade-off is uniform pipelines vs traceable, explicit code.

🛠 Real-world problems: how you handle them

Mapping lazily loaded orders fired 100 queries per page
Situation
Customer order-history endpoint at [company], about [150] requests a second at peak on Azure SQL in Australia East. The endpoint loaded 50 orders and mapped them with AutoMapper; lazy-loading proxies were enabled for the whole context.
Signals
Application Insights showed p95 for the endpoint at [~900 ms] and around [100] SQL dependency calls per request; Azure SQL DTU at [80%] during evening peaks; customers reported a slow 'My orders' page.
Investigation
Application Insights end-to-end transaction view showed one query for orders followed by a burst of small queries for `Customers` and `OrderLines`. EF Core SQL logging confirmed lazy loading triggered as the mapper read `Order.Customer.Name` and `Order.Lines`. `dotnet-counters` showed high allocation rate and Gen 0 GCs per request from tracked entity graphs.
Resolution
Immediate: added `Include` for customer and lines and `AsNoTracking` to stop the N+1. Real fix: replaced the read path with a Mapperly-generated `IQueryable<OrderDto>` projection, giving one SQL query with joins, and turned lazy loading off for the context.
Prevention
Turned lazy loading off by default; added an EF Core interceptor in integration tests that fails if a request runs more than [5] queries; made Mapperly unmapped-member diagnostics errors; added a code-review checklist item: read endpoints must project.

How to tell it (STAR)

**S:** At [company], our 'My orders' endpoint had a p95 of about [900 ms] at [150] requests a second, and Azure SQL was running hot every evening. **T:** I picked up the performance ticket and had to fix it without changing the API contract. **A:** Application Insights showed about [100] SQL calls per request; the mapper was triggering lazy loading for every order's customer and lines. I added `Include` and `AsNoTracking` as a hotfix, then replaced the read path with a Mapperly-generated projection that produced one query, turned lazy loading off, and added a test interceptor that fails on too many queries. **R:** p95 dropped to about [70 ms], DTU fell from [80%] to [35%], and the query-count test has since caught [two] similar regressions.

↩ Usually asked after

More in Enterprise Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me