# Valiant mapping Documentation version: 1. This context contains only this version. Source revision: 34222bb7277ce1a771ae4412d572b56f5eb98237. ## Mapping Source: https://valiant.staticnorth.dev/mapping/ # Mapping that stays visible Valiant Mapping turns a small mapper declaration into direct C# assignments. It handles conventional members, immutable targets, nested shapes, collections, enums, explicit transformations, conditional rules, and mapper composition—without runtime assembly scanning. ```csharp using StaticNorth.Valiant.Mapping; [ValiantMapper] public sealed partial class UserMapper : MapperDefinition; var dto = new UserMapper().Map(user); ``` The generated partial class implements `IMapper` and exposes a strongly typed `Map(User source)` method. ## Why use it? | Capability | What Valiant generates | | --- | --- | | Convention mapping | Direct reads and assignments for compatible public fields and properties | | Immutable targets | Constructor arguments for records and constructor-only models | | Shape changes | Flattening, unflattening, enum conversion, and reusable nested/collection mappers | | Explicit ownership | `Map`, `Ignore`, conditions, fallbacks, and null policy in `Configure` | | Runtime selection | Typed mapper, `IMapper` facade, and `IMapperFactory` through generated DI registration | | Deployment | A fast generated backend suited to trimming and Native AOT, plus a debuggable backend | :::tip Start with conventions Declare the mapper and compile. Add `Configure` only when the source and target shapes intentionally differ. Once `Configure` is present, list every target mapping you own explicitly. ::: ## Documentation map - [Quick start](https://valiant.staticnorth.dev/mapping/quick-start) — install, declare, register, and call a mapper. - [Runnable samples](https://valiant.staticnorth.dev/mapping/samples) — select and run every maintained Mapping scenario. - [Convention mapping](https://valiant.staticnorth.dev/mapping/guides/conventions) — records, constructors, flattening, collections, and enums. - [Explicit mapping](https://valiant.staticnorth.dev/mapping/guides/explicit-mapping) — transformations, conditions, ignores, fallbacks, and nulls. - [Composition and DI](https://valiant.staticnorth.dev/mapping/guides/composition-dependency-injection) — nested mappers, facade, and factory. - [Runtime and diagnostics](https://valiant.staticnorth.dev/mapping/reference) — modes, generated scope, warnings, and limitations. The [sample catalog](https://valiant.staticnorth.dev/mapping/samples) covers every executable Mapping scenario and links each one to its self-contained source folder. ## Quick start Source: https://valiant.staticnorth.dev/mapping/quick-start # Quick start ## 1. Install ```bash dotnet add package StaticNorth.Valiant.Mapping ``` `StaticNorth.Valiant.Mapping` contains the runtime API and delivers its source generator as an analyzer. No separate generator package is needed. ## 2. Declare the models and mapper ```csharp using StaticNorth.Valiant.Mapping; public sealed class User { public required string Name { get; init; } public int Age { get; init; } } public sealed record UserDto(string Name, int Age); [ValiantMapper] public sealed partial class UserMapper : MapperDefinition; ``` The mapper must be `partial`. `MapperDefinition` identifies the pair and the generator fills in the implementation. ## 3. Map ```csharp var mapper = new UserMapper(); var dto = mapper.Map(new User { Name = "Ada", Age = 36 }); ``` The mapper can also be consumed through its interface: ```csharp IMapper mapper = new UserMapper(); UserDto dto = mapper.Map(user); ``` ## 4. Register with dependency injection When the project references Microsoft dependency-injection abstractions, Valiant generates `AddValiantMappers`: ```csharp using StaticNorth.Valiant.Mapping.DependencyInjection; builder.Services.AddValiantMappers(options => { options.Mode = ValiantMappingMode.Auto; options.NullHandling = ValiantNullHandling.MapNulls; }); ``` Then inject the concrete mapper, `IMapper`, the non-generic `IMapper`, or `IMapperFactory`. :::info Generated discovery Only declarations marked with `[ValiantMapper]` enter the generator pipeline. Valiant does not scan every type in your compilation looking for mapping definitions. ::: Next: learn what maps automatically in [Convention mapping](https://valiant.staticnorth.dev/mapping/guides/conventions). ## Composition and dependency injection Source: https://valiant.staticnorth.dev/mapping/guides/composition-dependency-injection # Composition and dependency injection ## Reuse another mapper Constructor-inject the generated mapper and attach it to a member mapping: ```csharp [ValiantMapper] public sealed partial class AddressMapper : MapperDefinition; [ValiantMapper] public sealed partial class UserMapper(AddressMapper addressMapper) : MapperDefinition { public override void Configure(MappingContext context) { context.Map(source => source.Address, target => target.Address) .UseMapper(addressMapper); } } ``` `UseMapper` can be called on the context or in a fluent mapping chain. It makes nested object and collection-element conversion explicit and keeps each pair independently testable. ## Generated registration ```csharp using StaticNorth.Valiant.Mapping.DependencyInjection; builder.Services.AddValiantMappers(); ``` Valiant registers each mapper as its concrete type and as `IMapper`. It also registers `IMapper` and `IMapperFactory`. Mapper registrations are transient; the facade, factory, and options are singleton services. ## Choose an API ### Typed mapper Use the typed interface when the pair is known at compile time: ```csharp public sealed class UserHandler(IMapper mapper) { public UserDto Handle(User user) => mapper.Map(user); } ``` ### Non-generic facade Use `IMapper` when the source arrives as `object` but the target is known or supplied dynamically: ```csharp UserDto dto = mapper.Map(source); if (mapper.TryMap(source, typeof(UserDto), out var value)) { // value is the mapped object. } ``` ### Factory Use `IMapperFactory` when you need the mapper instance itself: ```csharp var typed = factory.CreateMapper(); if (factory.TryCreateMapper(typeof(User), typeof(UserDto), out var mapper)) { // mapper is the registered IMapper instance. } ``` Calls to `CreateMapper`/`Map` for a statically knowable unregistered pair produce analyzer diagnostics. Use the `Try...` APIs when absence is expected. ## Convention mapping Source: https://valiant.staticnorth.dev/mapping/guides/conventions # Convention mapping With no `Configure` override, Valiant maps public readable source fields and properties to public writable target fields, properties, or constructor parameters. ## Matching members Names are matched case-insensitively. Compatible values are assigned directly: ```csharp public sealed class Order { public Guid Id { get; init; } public decimal Total { get; init; } } public sealed class OrderDto { public Guid Id { get; init; } public decimal Total { get; init; } } [ValiantMapper] public sealed partial class OrderMapper : MapperDefinition; ``` ## Records and constructors Constructor parameters are mapped before writable members, so immutable targets work naturally: ```csharp public sealed record OrderDto(Guid Id, decimal Total); ``` Valiant chooses a usable public constructor and reports a compile-time diagnostic when the target cannot be constructed or a required member cannot be supplied. ## Flattening and unflattening Concatenated member paths can bridge nested and flat shapes: ```csharp public sealed class User { public required Address Address { get; init; } } public sealed class Address { public required string City { get; init; } } public sealed class UserDto { public required string AddressCity { get; init; } } ``` The reverse shape is supported when a flat source member can populate a nested target path. Prefer explicit mapping when concatenated names could be ambiguous. ## Enums Enums with compatible values map between enum types. Treat cross-domain enum contracts carefully: an explicit transformation is clearer when numeric values can drift independently. ## Nested objects and collections Register a mapper for the element or nested pair, then reuse it from the parent mapper: ```csharp [ValiantMapper] public sealed partial class LineMapper : MapperDefinition; [ValiantMapper] public sealed partial class OrderMapper(LineMapper lineMapper) : MapperDefinition { public override void Configure(MappingContext context) { context.Map(source => source.Lines, target => target.Lines) .UseMapper(lineMapper); } } ``` Valiant can apply the reusable mapper to compatible nested values and collection elements. See [Composition and dependency injection](https://valiant.staticnorth.dev/mapping/guides/composition-dependency-injection) for registration details. :::warning Explicit mode changes ownership Declaring `Configure` disables convention mapping for that mapper. Map or ignore every target member intentionally; diagnostics will identify missing or incompatible targets. ::: ## Explicit mapping Source: https://valiant.staticnorth.dev/mapping/guides/explicit-mapping # Explicit mapping Override `Configure` when names differ or a target value needs business-specific shaping: ```csharp [ValiantMapper] public sealed partial class UserMapper : MapperDefinition { public override void Configure(MappingContext context) { context .Map(source => source.EmailAddress, target => target.Email) .Map(source => $"{source.FirstName} {source.LastName}", target => target.DisplayName) .Ignore(target => target.InternalNote); } } ``` ## Conditional chains `When` applies to every declaration in the same fluent chain: ```csharp context .Map(source => source.EmailAddress, target => target.Email) .Map(source => source.Phone, target => target.Phone) .When(source => source.IncludeContactDetails); ``` Start a new statement when rules need different conditions. ## Defaults and fallbacks `Default` and `Fallback` are aliases. The value is used when a rule is skipped by its condition or ignores a null source value: ```csharp context.Map(source => source.DisplayName, target => target.DisplayName) .When(source => source.IsVisible) .Fallback("Hidden user"); ``` ## Null handling The mapper-wide default comes from `ValiantMappingOptions.NullHandling`: ```csharp services.AddValiantMappers(options => options.NullHandling = ValiantNullHandling.IgnoreSourceNulls); ``` Override it per rule: ```csharp context.Map(source => source.Nickname, target => target.Nickname) .IgnoreNull(); context.Map(source => source.AvatarUrl, target => target.AvatarUrl) .MapNull(); // AllowNull() is an alias. ``` | API | Effect | | --- | --- | | `IgnoreNull()` | Leave the target value unchanged when the source expression returns `null` | | `MapNull()` | Assign `null`, even when mapper options ignore source nulls | | `AllowNull()` | Alias for `MapNull()` | | `Default(value)` | Use a value when the rule is skipped or a null is ignored | | `Fallback(value)` | Alias for `Default(value)` | ## Intentional omissions Use `Ignore` to document that a writable or required target member is intentionally not populated: ```csharp context.Ignore(target => target.AuditStamp); ``` This is preferable to suppressing an unmapped-member warning because the decision remains beside the rest of the mapping contract. Run the conditional and null-policy variants from the [Mapping sample catalog](https://valiant.staticnorth.dev/mapping/samples). ## Runtime, generation, and diagnostics Source: https://valiant.staticnorth.dev/mapping/reference # Runtime, generation, and diagnostics ## Runtime options ```csharp services.AddValiantMappers(options => { options.Mode = ValiantMappingMode.Auto; options.NullHandling = ValiantNullHandling.MapNulls; }); ``` | Option | Values | Default | | --- | --- | --- | | `Mode` | `Auto`, `Debuggable`, `Fast` | `Auto` | | `NullHandling` | `MapNulls`, `IgnoreSourceNulls` | `MapNulls` | `Auto` uses the debuggable runtime backend in Debug builds and direct generated mapping in other builds. `Debuggable` executes your `Configure` method at runtime, so breakpoints work; this path uses expression compilation and reflection. `Fast` always uses generated direct mapping code and is the preferred deployment path for trimming and Native AOT. ## Generator scope `[ValiantMapper]` is the discovery boundary. The incremental generator processes only marked declarations and emits: - the typed `Map` implementation and `IMapper` contract; - direct member/constructor mapping for the fast backend; - mapper registration metadata; - `AddValiantMappers` when dependency-injection abstractions are present. A separate narrowly scoped analyzer checks statically knowable `IMapper` and `IMapperFactory` calls for missing pairs without putting ordinary invocations into the generator graph. ## Diagnostics | ID | Meaning | | --- | --- | | `VLM001` | Mapper must be partial | | `VLM002` | Mapper shape is unsupported | | `VLM003` | Source/target pair cannot be determined | | `VLM004` | Mapping declaration syntax is unsupported | | `VLM005` | Target cannot be constructed | | `VLM006` | Required target member is not mapped | | `VLM101` | A target member is not mapped | | `VLM102` | A source member exists but its type is incompatible | | `VLM104` | More than one default mapper owns the same pair | | `VLM105` | `IMapperFactory` call requests an unregistered pair | | `VLM106` | `IMapper` facade call requests an unregistered pair | ## Constraints - Mapper and containing declarations that receive generated members must be `partial`. - Each source/target pair has one default generated mapper. - Targets need a usable public construction path. - `Configure` is intentionally generator-readable; unsupported expression shapes produce `VLM004` instead of silently changing behavior. - Use `TryMap` or `TryCreateMapper` for pairs that are optional at runtime. ## Samples Source: https://valiant.staticnorth.dev/mapping/samples # Mapping samples Select one delegate near the top of [`Program.cs`](https://github.com/static-north-dev/valiant/blob/main/mapping/samples/StaticNorth.Valiant.Mapping.Samples/Program.cs), then run: ```bash dotnet run --project mapping/samples/StaticNorth.Valiant.Mapping.Samples ``` `Program.cs` is intentionally only a selector. Each folder is self-contained, and the `Sample` class owns the explanation of the behavior it invokes. | Delegate | Demonstrates | Source | | --- | --- | --- | | `Basic.Sample.Run` | The smallest useful mapper: matching members mapped by convention into an immutable constructor target | [`Basic`](https://github.com/static-north-dev/valiant/tree/main/mapping/samples/StaticNorth.Valiant.Mapping.Samples/Basic) | | `ExplicitMapping.Sample.Run` | A custom source transform, a renamed target member, and an intentionally ignored target member | [`ExplicitMapping`](https://github.com/static-north-dev/valiant/tree/main/mapping/samples/StaticNorth.Valiant.Mapping.Samples/ExplicitMapping) | | `ConditionalMapping.Sample.Run` | Native `if`/`else`, a chained `When` condition, and the equivalent `Fallback` and `Default` APIs | [`ConditionalMapping`](https://github.com/static-north-dev/valiant/tree/main/mapping/samples/StaticNorth.Valiant.Mapping.Samples/ConditionalMapping) | | `NullHandling.Sample.Run` | Mapper-wide null policy, `IgnoreNull`, `MapNull`, `AllowNull`, and a fallback for an ignored null | [`NullHandling`](https://github.com/static-north-dev/valiant/tree/main/mapping/samples/StaticNorth.Valiant.Mapping.Samples/NullHandling) | | `FlatteningAndEnums.Sample.Run` | Convention-based flattening, unflattening, and compatible enum conversion | [`FlatteningAndEnums`](https://github.com/static-north-dev/valiant/tree/main/mapping/samples/StaticNorth.Valiant.Mapping.Samples/FlatteningAndEnums) | | `Composition.Sample.Run` | Constructor-injected mapper reuse for a nested object and collection elements | [`Composition`](https://github.com/static-north-dev/valiant/tree/main/mapping/samples/StaticNorth.Valiant.Mapping.Samples/Composition) | | `DependencyInjection.Sample.Run` | Generated registration; typed mapper, non-generic facade, and factory; successful and missing `Try` APIs | [`DependencyInjection`](https://github.com/static-north-dev/valiant/tree/main/mapping/samples/StaticNorth.Valiant.Mapping.Samples/DependencyInjection) | The basic and convention samples show what the generator can infer. Samples with a `Configure` override demonstrate behavior supported by both the debuggable runtime backend and the fast generated backend. The dependency injection sample leaves `ValiantMappingMode.Auto` selected, so Debug builds use the debuggable backend and Release builds use generated fast mapping. Continue with [Convention mapping](https://valiant.staticnorth.dev/mapping/guides/conventions), [Explicit mapping](https://valiant.staticnorth.dev/mapping/guides/explicit-mapping), or [Composition and dependency injection](https://valiant.staticnorth.dev/mapping/guides/composition-dependency-injection) for the complete contracts and constraints.