
Mapping Libraries Don't Remove Mapping Bugs: Mapster vs Manual Mapping
- كاتب موثّق
- .NET 10
محتويات المقال
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
FirstName = src.LastName typos.
What actually happens
Conventions fill what matches and skip the rest
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.
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
Pending added first to the contract enum, Active became Pending, Suspended became Active and Closed became Suspended.
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
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.
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
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
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);}using Mapster;public static class MappingConfig{ // Call once at startup, and again from a unit test public static void Register(TypeAdapterConfig config) { config.RequireExplicitMapping = true; // no unregistered pairs config.RequireDestinationMemberSource = true; // no unmapped members config.Default.EnumMappingStrategy(EnumMappingStrategy.ByName); config.NewConfig<Customer, CustomerDto>() .Map(dest => dest.Email, src => src.EmailAddress); // Throws a CompileException naming any unmapped member config.Compile(); }}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:
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;}CompileException naming it | required | ||
CompileException | |||
switch | |||
null in an update request | IgnoreNullValues | ||
How to apply it in your project
Turn on both strict modes Set RequireExplicitMappingandRequireDestinationMemberSourceon the configuration your app uses, then register every pair withNewConfig.Compile at startup and in a test Call 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.Map enums by name and test every value Switch to EnumMappingStrategy.ByName, then map each value ofEnum.GetValues<T>()in a test, because a missing name fails only at run time.Write the write path by hand Replace 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 requiredmembers lets the compiler catch missing members, and Mapster doesn't enforcerequiredat all.A practical split: Mapster with strict checks for reads, explicit code for writes.
التعليقات (0)