الانتقال إلى المحتوى
.NETMapster· 7 دقائق للقراءة

Mapping Libraries Don't Remove Mapping Bugs: Mapster vs Manual Mapping

Mapster saves the typing, not the decisions. By default a member with no match stays empty and enums map by number, silently, until you turn on its checks or let the compiler check hand-written mapping.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

A refactor renames Customer.Email to EmailAddress across the domain. The build is green and every test passes. Two days later, support forwards a complaint: the customer screen shows no email, for anyone. The endpoint returns customer.Adapt<CustomerDto>(), and CustomerDto.Email now has nothing to match, so it's null. The same week, someone adds Pending to the top of the contract's status enum, and suspended customers start showing up as active. Nothing failed. Mapster did exactly what its conventions say.

The common misconception

The belief: a convention-based mapper like Mapster removes mapping bugs, because it maps matching properties automatically. No hand-written assignments means no forgotten lines and no FirstName = src.LastName typos.

It's an easy belief to hold. Hand-written mapping really is where typos live, and a project with fifty DTOs has a lot of it that nobody reviews carefully. Mapster's README opens with "Writing mapping methods is a machine job", and for the simple case it's right: same names and types map correctly, and fast. The half-truth is that the typing goes away but the decisions don't. Which source feeds which member, and what a missing one means, are still decided, now by conventions at run time instead of by code the compiler reads.

What actually happens

Conventions fill what matches and skip the rest

Mapster maps a destination member when it finds a source member with the same name, a GetX() method, or a path such as Address.City for AddressCity. When it finds nothing, it leaves the member alone. That's the documented default: RequireDestinationMemberSource is false. In a test with Mapster 10.0.14, after the rename, Email came back null with no exception, warning or log line.

A required member doesn't save you either. The compiler enforces required only in object initializers it compiles, and Mapster builds its objects at run time. In the same test, a DTO declaring required string Email was created with Email set to null.

A match isn't always the right match

Names also line up by accident. Mapster's data-types page says an enum mapped to a different enum type is mapped by value unless you configure otherwise. In the test, with Pending added first to the contract enum, Active became Pending, Suspended became Active and Closed became Suspended.

Mapping onto an existing object has the same blind spot. The docs state that Mapster maps every matching property by default, even when the source value is null. request.Adapt(customer) with an empty Name wiped the stored name, and any request property that happens to share a name with an entity member flows straight in, which is how starts.

Mapster checks only when you ask

Mapster has strict modes for this. RequireDestinationMemberSource demands a source, or an explicit map or ignore, for every destination member, and RequireExplicitMapping demands a registered configuration for every type pair. Calling Compile() validates the configuration, and the wiki recommends doing it at startup so problems show up then rather than mid-request. In the test, Compile() threw a CompileException whose inner exception named the unmapped Email member.

Two details matter. Compile() checks only the pairs it knows: with no pairs registered, it passed, and the bad pair failed later, at its first Adapt. RequireExplicitMapping is what makes Compile() cover everything. And it checks shape, not meaning. With enums mapped by name, a domain value missing from the contract enum passed Compile() and threw a FormatException the first time a Closed customer was mapped.

Manual mapping moves the check to the compiler

Hand-written mapping fails differently: a forgotten line, a swapped property. But give the DTO required members and forgetting one is a compile error (CS9035), and a renamed source property breaks the build where it's used. Mapster's own README lists the same benefit for its code generation, Mapster.Tool: generated mapping code is validated at compile time and is code you can read and debug. One gap remains in every approach: nothing notices a new entity property that should have been exposed. That's a review question.

The fix: make mapping fail loudly

C# CustomerMappings.cs
using Mapster;public static class CustomerMappings{    // Compiles and runs. After the rename, Email is null, and Status is    // copied by number, so Suspended becomes Active.    public static CustomerDto ToDto(Customer customer) =>        customer.Adapt<CustomerDto>();    // Copies every member whose name matches, Name = null included    public static void Apply(UpdateCustomer request, Customer customer) =>        request.Adapt(customer);}

With this configuration, the test mapped Suspended to Suspended and Email correctly, and deleting the .Map(...) line made Compile() fail with the member's name. When you'd rather have the compiler do the checking, write it out:

C# CustomerMapper.cs
public sealed class CustomerSummary{    public required int Id { get; init; }    public required string Email { get; init; }}public static class CustomerMapper{    // A new required member breaks this method at compile time (CS9035)    public static CustomerSummary ToSummary(Customer c) =>        new() { Id = c.Id, Email = c.EmailAddress };    // Writes name the fields a request may change, nothing else    public static void Apply(UpdateCustomer request, Customer customer) =>        customer.Name = request.Name ?? customer.Name;}
FailureMapster defaultsMapster, strict and compiledManual mapping
DTO member with no sourceLeft at default, silentlyCompileException naming itCompile error with required
Source member renamedDestination goes emptyCompileExceptionCompile error
Enum values out of orderCopied by numberCorrect by name; a missing name throws at first useYou write the switch
null in an update requestCopied over stored dataCopied unless IgnoreNullValuesYou decide per field
New entity property never exposedNot noticedNot noticedNot noticed

How to apply it in your project

  1. Turn on both strict modesSet RequireExplicitMapping and RequireDestinationMemberSource on the configuration your app uses, then register every pair with NewConfig.
  2. Compile at startup and in a testCall Compile() once all configuration is done, since the wiki notes that changing settings after compiling causes errors. Run the same registration from a unit test.
  3. Map enums by name and test every valueSwitch to EnumMappingStrategy.ByName, then map each value of Enum.GetValues<T>() in a test, because a missing name fails only at run time.
  4. Write the write path by handReplace request.Adapt(entity) with methods that set only the members a request may change.

Key takeaways

  • Mapster removes the typing in mapping code, not the decisions; conventions make them at run time.
  • By default, unmatched members stay empty, enums map by number and nulls overwrite data, all silently.
  • Strict mode plus Compile() in a test turns most drift into a named failure, but only for registered pairs and only for shape, not meaning.
  • Hand-written mapping with required members lets the compiler catch missing members, and Mapster doesn't enforce required at all.
  • A practical split: Mapster with strict checks for reads, explicit code for writes.

📚 المصادر

  1. Mapster README — MapsterMapper/Mapster on GitHub
  2. Config validation & compilation — Mapster wiki
  3. Data types (enums, mappable objects, flattening) — Mapster wiki
  4. Ignoring members (IgnoreNullValues) — Mapster wiki
  5. required modifier — C# reference, Microsoft Learn

التعليقات (0)