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.
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:
ProjectTo. Since v15.0 (July 2025) it's dual-licensed RPL-1.5/commercial (Lucky Penny Software), free for companies under US$5M revenue.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.
"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, andProjectTo<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 callAssertConfigurationIsValidin a test, and complex profiles withForMemberand 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 declarepartialmethods 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 anIQueryable<Order>toIQueryable<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."
| 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 |
| 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 |
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%.
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
AssertConfigurationIsValid or build diagnostics for unmapped members.Select/ProjectTo on reads.Red flags
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)
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.
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.
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:
.editorconfig to fail the build).[MapProperty], [MapperIgnoreTarget] handle exceptions to the convention.IQueryable<TTarget> from IQueryable<TSource> generates a Select expression that EF Core translates.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.
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.
[MemoryDiagnoser]).ToListAsync() then map vs a projection, with LogTo(Console.WriteLine).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
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.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.ProjectTo. Instead: Compute values in the domain or query; keep mapping dumb.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.
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.
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.
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.
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.
Last updated 18 Nov 2026.