ZetCode

C# Mapster

last modified November 15, 2026

This article shows how to map objects in C# with Mapster. We cover basic and nested mapping, configuration rules, ignoring and conditional members, updating existing objects, global registration, and LINQ projections.

Object-to-object mapping copies data from one type to another. A program often keeps the same information in several shapes: a persistence entity, a domain model, an API contract, and a view model. Writing the copy by hand is explicit but repetitive, and every new property adds another line that can be forgotten. A mapper derives the copy from the structure of the two types.

Mapster is a convention-based mapper for .NET. It matches members by name, maps nested objects and collections recursively, and compiles the mapping into a delegate that is cached for later calls. Naming differences, computed values, and security rules are expressed with a small configuration API. The examples use Mapster 10.0.14, which is MIT-licensed. Add it to a project with dotnet add package Mapster; the namespace is Mapster.

Basic mapping

The Adapt<TDestination> method creates a destination object from a source object. For two types whose members have the same names, no configuration is needed.

Program.cs
using Mapster;

var user = new User(1, "Alice", "Smith", "alice@example.com");

UserDto dto = user.Adapt<UserDto>();
Console.WriteLine($"{dto.Id} {dto.FirstName} {dto.LastName} {dto.Email}");

public record User(int Id, string FirstName, string LastName, string Email);

public record UserDto(int Id, string FirstName, string LastName, string Email);

Both types declare the same four positional parameters, so every destination value comes from the matching source member. The source object is not modified, and the destination is a new instance.

UserDto dto = user.Adapt<UserDto>();

Adapt is an extension method whose type argument is the destination. The first call inspects the two types and builds a mapping expression; the result is cached, so later calls with the same type pair run the already prepared code. The destination is a separate object graph: nested reference values are mapped to new instances as well, so a DTO does not share state with its source.

Members are matched by name without regard to case, so a source property Name fills a destination property name. A destination member with no matching source keeps its default value (null, 0, or false), and a source member with no destination is ignored. That silence is convenient for simple shapes and dangerous for important ones: a misspelled destination member receives a default instead of an error. Configuration, shown below, turns the important parts into explicit rules.

$ dotnet run
1 Alice Smith alice@example.com

Nested objects and collections

Real models rarely consist of flat types. An order has a customer, the customer has an address, and the order has a collection of lines. Mapster walks the whole graph and maps each type it encounters.

Program.cs
using Mapster;

var order = new Order(
    1001,
    new Customer("Alice", "Smith", new Address("Main Street", "Bratislava", "811 01")),
    new[] { new OrderLine("Keyboard", 2, 49.90m), new OrderLine("Mouse", 1, 24.50m) });

OrderDto dto = order.Adapt<OrderDto>();

Console.WriteLine($"{dto.Id} {dto.Customer.FullName}");
Console.WriteLine($"{dto.Customer.Address.City} {dto.Customer.Address.PostalCode}");
foreach (var line in dto.Lines)
{
    Console.WriteLine($"{line.Product} x{line.Quantity} = {line.Total:F2}");
}

public record Address(string Street, string City, string PostalCode);
public record Customer(string FirstName, string LastName, Address Address)
{
    public string FullName => $"{FirstName} {LastName}";
}
public record OrderLine(string Product, int Quantity, decimal UnitPrice)
{
    public decimal Total => Quantity * UnitPrice;
}
public record Order(int Id, Customer Customer, OrderLine[] Lines);

public record AddressDto(string Street, string City, string PostalCode);
public record CustomerDto(string FirstName, string LastName, AddressDto Address)
{
    public string FullName => $"{FirstName} {LastName}";
}
public record OrderLineDto(string Product, int Quantity, decimal UnitPrice)
{
    public decimal Total => Quantity * UnitPrice;
}
public record OrderDto(int Id, CustomerDto Customer, OrderLineDto[] Lines);

Each nested type has a destination counterpart. The customer and address are mapped as objects, and the array of order lines becomes an array of OrderLineDto. The computed FullName and Total properties are not copied; they are calculated from the values that were copied.

OrderDto dto = order.Adapt<OrderDto>();

Collections are mapped element by element. A List<T>, an array, or any IEnumerable<T> source can fill a compatible destination collection whose element type is itself mappable. The destination collection is a new instance, so changing the DTO does not change the source order.

A get-only property such as Total cannot be assigned, and Mapster does not try to. It is enough that the constructor parameters are matched; the property then calculates its value from them. If a destination type has a settable property with no source counterpart, it keeps its default value instead.

$ dotnet run
1001 Alice Smith
Bratislava 811 01
Keyboard x2 = 99.80
Mouse x1 = 24.50

Configuring mappings

Convention fails when the names differ. A destination may expose a single FullName where the source stores FirstName and LastName, or call an email field EmailAddress while the source calls it Email. A TypeAdapterConfig holds explicit rules for such pairs.

Program.cs
using Mapster;

var config = new TypeAdapterConfig();
config.NewConfig<User, UserDto>()
    .Map(dest => dest.FullName, src => $"{src.FirstName} {src.LastName}")
    .Map(dest => dest.EmailAddress, src => src.Email);

var user = new User(1, "Alice", "Smith", "alice@example.com");
UserDto dto = user.Adapt<UserDto>(config);

Console.WriteLine($"{dto.Id} {dto.FullName} {dto.EmailAddress}");

public record User(int Id, string FirstName, string LastName, string Email);

public record UserDto(int Id, string FullName, string EmailAddress);

The destination has no member called FirstName, LastName, or Email, so convention alone cannot fill FullName and EmailAddress. The two Map calls supply the missing rules, while Id continues to map by name.

config.NewConfig<User, UserDto>()
    .Map(dest => dest.FullName, src => $"{src.FirstName} {src.LastName}")
    .Map(dest => dest.EmailAddress, src => src.Email);

NewConfig creates a mapping for one source-destination pair. Map takes an expression that selects the destination member and an expression that produces its value from the source. The expressions are analyzed once, when the configuration is built, and the resulting delegate is reused for every object. The first argument is checked by the compiler, so renaming a destination property breaks the configuration instead of silently producing a default.

The configuration instance is passed to Adapt. A different instance can hold a different set of rules, which is useful in tests: nothing is registered globally, and the test can build exactly the mapping it needs. In an application, build the configuration once during startup and reuse it; rebuilding it per request throws away the compiled delegates.

$ dotnet run
1 Alice Smith alice@example.com

Ignoring and conditional members

Some source members must never reach the destination. An update model that comes from an HTTP request may contain an IsAdmin flag, while the entity it updates also has that flag. Convention would copy the value, and a client could promote itself. Ignore removes the member from the mapping.

Program.cs
using Mapster;

var config = new TypeAdapterConfig();
config.NewConfig<UserUpdate, User>()
    .Ignore(dest => dest.IsAdmin)
    .Map(dest => dest.DisplayName, src => src.Nickname, src => !string.IsNullOrWhiteSpace(src.Nickname));

var user = new User { Id = 7, Name = "Alice", DisplayName = "Alice", IsAdmin = false };
var update = new UserUpdate("Alice Smith", "ally", true);

update.Adapt(user, config);

Console.WriteLine($"{user.Id} {user.Name} {user.DisplayName} {user.IsAdmin}");

public record UserUpdate(string Name, string? Nickname, bool IsAdmin);

public class User
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public string DisplayName { get; set; } = "";
    public bool IsAdmin { get; set; }
}

The source asks for IsAdmin = true, but the destination keeps false because the member is not part of the mapping. The Name member is copied by convention, and DisplayName is replaced by the nickname.

config.NewConfig<UserUpdate, User>()
    .Ignore(dest => dest.IsAdmin)
    .Map(dest => dest.DisplayName, src => src.Nickname, src => !string.IsNullOrWhiteSpace(src.Nickname));

The three-argument Map overload adds a condition that is evaluated against the source before the value is assigned. When the nickname is missing or blank, the condition is false and DisplayName is left untouched, so the update does not erase an existing value with an empty string. The condition can use any source member and runs once per object.

Ignore is stronger than a condition: the destination member is excluded from the mapping entirely, even if the source later gains a member with the same name. That makes it suitable for fields such as identifiers, audit timestamps, roles, and ownership that the server assigns rather than the client.

$ dotnet run
7 Alice Smith ally False

Updating existing objects

Creating a new object is not always what a program needs. A patch request carries only the fields the caller wants to change, and those values must be applied to an object that already exists. Mapster has an Adapt overload that writes into a destination instance instead of creating one.

Program.cs
using Mapster;

var config = new TypeAdapterConfig();
config.Default.IgnoreNullValues(true);

var user = new User { Id = 7, Name = "Alice", Email = "alice@example.com" };
var patch = new UserPatch { Name = null, Email = "new@example.com" };

patch.Adapt(user, config);

Console.WriteLine($"{user.Id} {user.Name} {user.Email}");

public class User
{
    public int Id { get; set; }
    public string? Name { get; set; }
    public string? Email { get; set; }
}

public class UserPatch
{
    public string? Name { get; set; }
    public string? Email { get; set; }
}

The patch has no Id, so the existing identifier is preserved. Name is null, which means the caller did not send a new value, and the stored name stays Alice. The email is present and replaces the old one.

config.Default.IgnoreNullValues(true);

The setting applies to every mapping in that configuration: a null source member does not overwrite the destination. Without it, Name would become null. Treat null as "not supplied" only when the protocol defines it that way; if an explicit null must clear a field, the patch type needs a separate flag, or the field needs its own rule.

patch.Adapt(user, config);

This overload mutates the instance passed as the second argument and returns it. The source is mapped onto the existing object, so members that have no source counterpart, such as Id, are left as they are. Because the destination is not constructed here, constructor-based records are not a good fit for this pattern; use classes with settable properties.

$ dotnet run
7 Alice new@example.com

Global configuration

Mapping rules usually live in one or more IRegister implementations. Each class declares the rules for a group of types, and a scan at startup finds every implementation in an assembly. This keeps the rules out of the request path and makes them easy to locate.

Program.cs
using Mapster;

var config = new TypeAdapterConfig();
config.Scan(typeof(Program).Assembly);

var user = new User(1, "Alice", "Smith", "alice@example.com");
UserDto dto = user.Adapt<UserDto>(config);

Console.WriteLine($"{dto.Id} {dto.FullName} {dto.EmailAddress}");

public record User(int Id, string FirstName, string LastName, string Email);

public record UserDto(int Id, string FullName, string EmailAddress);

public class MappingRegister : IRegister
{
    public void Register(TypeAdapterConfig config)
    {
        config.NewConfig<User, UserDto>()
            .Map(dest => dest.FullName, src => $"{src.FirstName} {src.LastName}")
            .Map(dest => dest.EmailAddress, src => src.Email);
    }
}

The register class is discovered by the scan, its Register method runs once, and the resulting configuration maps the user. The Program type simply identifies the assembly to search.

config.Scan(typeof(Program).Assembly);

Scan finds public and internal classes that implement IRegister and calls each one with the configuration being built. In an ASP.NET Core application, services.AddMapster() from the Mapster.DependencyInjection package registers the configuration and the adapter with the container. The static TypeAdapterConfig.GlobalSettings is the configuration used when Adapt is called without one; an explicit instance is easier to reason about in tests because it avoids shared state.

$ dotnet run
1 Alice Smith alice@example.com

Projection

Mapping in memory first materializes the whole source object, even when the caller needs only a few members. A projection instead builds a LINQ expression that selects the destination shape, so a query provider can fetch only the required columns. Mapster provides ProjectToType<TDestination> for this.

Program.cs
using Mapster;

var products = new List<Product>
{
    new(1, "Keyboard", 49.90m, "Peripherals"),
    new(2, "Mouse", 24.50m, "Peripherals"),
    new(3, "Monitor", 199.00m, "Displays")
}.AsQueryable();

var cheap = products
    .Where(p => p.Price < 100m)
    .ProjectToType<ProductDto>()
    .ToList();

foreach (var p in cheap)
{
    Console.WriteLine($"{p.Id} {p.Name} {p.Price:F2} {p.Category}");
}

public record Product(int Id, string Name, decimal Price, string Category);

public record ProductDto(int Id, string Name, decimal Price, string Category);

The filter runs before the projection, and the result contains only the two products below one hundred. The destination type happens to have the same members as the source, which makes the difference between projection and mapping easy to miss.

var cheap = products
    .Where(p => p.Price < 100m)
    .ProjectToType<ProductDto>()
    .ToList();

On an IQueryable backed by Entity Framework Core, the expression is translated to SQL, and the database returns only the selected columns. With AsQueryable() over a list, the same expression runs in memory. Explicit Map rules can be used in a projection only if the provider can translate them; a rule that calls an arbitrary method will fail at query time, so keep projections simple or map after materialization.

$ dotnet run
1 Keyboard 49.90 Peripherals
2 Mouse 24.50 Peripherals

Compiled mappings and code generation

Mapster builds a mapping expression on first use and caches it. For a service that should fail at startup rather than during the first request, config.Compile() builds every registered mapping immediately and reports configuration problems before traffic arrives. This is a deployment safeguard, not a performance requirement for small programs.

Reflection-based mapping is inconvenient for Native AOT and for assemblies that are trimmed, because the mapper needs member metadata at run time. Mapster.Tool generates the mapping code at build time from [AdaptTo] and [AdaptFrom] attributes, or from a model file, so the application ships ordinary C# instead of reflection calls. The generated code can be read, debugged, and stepped through like any other source file.

Limitations

Convention covers members with the same names and compatible types. It does not know that FullName should combine two fields, that IsAdmin must not be copied, or that a price needs rounding. Those are configuration, and configuration is code that must be reviewed and tested like any other.

Mapping is also not validation. A missing source value becomes a default, and a destination with a non-nullable string can end up with an empty value rather than an error. Validate the input before mapping, and keep the mapping rules close to the types they serve. For Entity Framework Core, project directly to the DTO instead of mapping loaded entities, so lazy loading and change tracking do not pull more data than the response needs.

The records, LINQ, and JSON tutorials cover the types and queries used in the examples. The expression trees tutorial explains how a mapper turns lambdas into reusable delegates.

Source

Mapster on GitHub

Mapster documentation

Mapster on NuGet

In this article we have mapped objects in C# with Mapster. See also the records, LINQ, JSON, and expression trees tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.