Mappa.Generator
10.1.0
dotnet add package Mappa.Generator --version 10.1.0
NuGet\Install-Package Mappa.Generator -Version 10.1.0
<PackageReference Include="Mappa.Generator" Version="10.1.0"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference>
<PackageVersion Include="Mappa.Generator" Version="10.1.0" />
<PackageReference Include="Mappa.Generator"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference>
paket add Mappa.Generator --version 10.1.0
#r "nuget: Mappa.Generator, 10.1.0"
#:package Mappa.Generator@10.1.0
#addin nuget:?package=Mappa.Generator&version=10.1.0
#tool nuget:?package=Mappa.Generator&version=10.1.0
Mappa.Generator
This source generator generates code for partial methods in partial classes tagged with the [Mappa] attribute defined in the Mappa package.
The generated code allow to map from a source type to a target type.
Assuming you have a partial method like the following
[Mappa]
public partial class Mapper
{
public partial TTarget Map(TSource input);
}
where TSource is the source type of the mapping and TTarget is the target type of the mapping, the source generator works by applying the strategies described below (see TypeMapIdentifierAlgorithm.cs).
The methods that can be auto-generated by πΊοΈ Mappa need to satisfy the following:
- The class they belong to needs to be marked with the
[Mappa]attribute; - The class they belong to needs to be partial;
- The method needs to be partial;
- The method must return a non-
voidtype; - The method must not return a
Task<T>(i.e. mapper methods cannot beasync); - The method must have one or two parameters; if the method has two parameters, the second must be of type
Mappa.MappaContext; - Methods marked with
[MappaIgnore]are excluded from mapping resolution; - Non-partial methods with an existing implementation can be registered as pre-mapped (used when resolving nested mappings);
- Methods from the mapper base-class hierarchy are collected automatically;
- Parameter ref modifiers must be absent or
in; any other ref modifier causes the method to be rejected.
Strategy resolution overview
Resolution follows one of two paths depending on whether the mapping is the root partial method or a nested type mapping (collection elements, dictionary keys/values, tuple items, constructor parameters, or property initializers).
Root partial methods
Root partial methods use TypeMapIdentifierAlgorithm, which runs the detector chain described below. Root methods do not invoke an existing map method for themselves.
Nested type mappings
Nested mappings use TypeMapIdentifierWithMapMethodAlgorithm, which runs an existing-method pre-step first (see below). If no existing method applies, the same detector chain is used.
Existing-method pre-step (nested mappings only)
Before the detector chain, TypeMapIdentifierWithMapMethodAlgorithm checks whether a suitable map method already exists:
- When:
- A method in the same class or a base class of the mapper from
TSourcetoTTargetexists OR, - A method from a property or field marked with the
[MappaDependency]on the mapper or an accessible base class of the mapper, or from a base class of the dependency type fromTSourcetoTTargetexists OR, - A method from a type defined via the
[MappaStaticDependency]attribute exists OR, - A polymorphic method where one of the
[MappaTypeMapping]attributes matchesTSourceandTTargetOR, - Setting
PolymorphicMapMethodWithMatchingDefaultAttributeisEnableand a polymorphic method with attribute[MappaTypeMappingDefault]and behaviourMappaTypeMappingDefaultBehavior.MapSourceType, whereTTargetmatches the target type defined by the attribute andTSourcematches the source type of the method, exists;
- A method in the same class or a base class of the mapper from
- What:
- The existing method is invoked;
- Notes:
- A nested mapper method that requires
MappaContextis only invoked when the caller provides context (the root map method has aMappaContextparameter); - This pre-step is used when mapping elements of an array, keys or values of dictionaries, elements of tuples, and properties or constructor parameters of class/struct/record types.
- A nested mapper method that requires
Detector chain order
When no existing method applies (or for root methods), TypeMapIdentifierAlgorithm tries the following strategies in order:
- Identity (skipped when the root method has one or more
[MappaTypeMapping]attributes) - Nullable
- Polymorphic (only at the root, or immediately after nullable unwrapping β not at every nested level)
- Enum
- String
- Date & time
- Container
- Tuple
- Guid
- Constructor
Strategy details
1. Identity strategy
- When:
TSourceandTTargetare the same type (e.g.TSource => intandTTarget => int) OR,TSourcecan be implicitly converted intoTTarget(e.g.TSource => intandTTarget => long) OR,TSourcemaps toobjectorobject?(nullable-context rules apply: in#nullable enable,Tmaps toobject?; in#nullable disable,Tmaps toobject; when the source is not explicitly non-nullable annotated,Tmay map to non-nullableobject);
- What:
- By default (
ShallowCopy), the input value is assigned to the target; - When
IdentityMapDeepCopyisDeepCopyon a reference-type same-type root, the mapper clones the instance viaMappa.MappaCloning.MemberwiseClone(nested references remain shared); - When
IdentityMapDeepCopyisNestedDeepCopyon a reference-type root, the mapper clones the instance and recursively maps every accessible instance field; on a struct root, the struct is copied and fields are mapped recursively (noMemberwiseCloneon the struct itself); - Primitives, enums, and
stringsame-type mappings always assign and ignoreIdentityMapDeepCopy;
- By default (
- Notes:
DateTimeβDateTimeOffsetis handled by the identity strategy (implicit conversion);- The identity detector is skipped when the root method has
[MappaTypeMapping]attributes so that polymorphic mapping can run instead; - Same-type constructor-parameter identity in the constructor detector always uses shallow pass-through;
IdentityMapDeepCopyapplies only when the identity strategy is selected directly; NestedDeepCopyon array or collection same-type roots falls through to the container strategy so elements are mapped;- Nested field resolution disables the identity detector to avoid infinite recursion.
2. Nullable strategy
- When:
TSourceis theNullable<T>value type (e.g.int?) OR,TSourceis a nullable reference type when#nullable enable(e.g.string?) OR,TSourceis a reference type when#nullable disable(e.g.stringβ treated as a nullable source, consistent withIsReferenceNullable) OR,TTargetis a nullable value type andTSourceis the corresponding non-nullable value type,- AND a mapping exists from source to target when nullability is stripped (or, for nullable target / non-nullable source, a mapping exists for the inner types);
- What:
- When the source is nullable: if
TTargetcan benull, the mapper returnsnull; ifTTargetcannot benull, the mapper throws aNullReferenceException; - When the target is nullable and the source is non-nullable: the inner type is mapped without a nullable wrapper;
- When the source is nullable: if
- Notes:
- After nullable unwrapping, the polymorphic detector may run if the root method has
[MappaTypeMapping]attributes.
- After nullable unwrapping, the polymorphic detector may run if the root method has
3. Polymorphic mapping
- When:
- The root method has one or multiple
[MappaTypeMapping]attributes, and the polymorphic detector is allowed to run (at the root, or immediately after the nullable detector);
- The root method has one or multiple
- What:
- The runtime type of the input determines how the mapping from
TSourcetoTTargethappens; - For every
[MappaTypeMapping]attribute a mapping is created; - The default mapping when the actual parameter type does not match any source type from the
[MappaTypeMapping]attributes is determined by the[MappaTypeMappingDefault]attribute β if the attribute is not present, the default behaviour throws an exception;
- The runtime type of the input determines how the mapping from
- Notes:
- The polymorphic detector does not run at every nested level; it runs only at the root or immediately after nullable unwrapping.
4. Enum strategy
- When:
TSourceis anenumandTTargetis a differentenum, an integral numeric type compatible with the enum, or astringOR,TSourceis an integral numeric type compatible with the enum andTTargetis anenumOR,TSourceis astringandTTargetis anenum;
- What:
- Enum β enum and enum β string: a
switchstatement maps by shared enum member names, by shared underlying numeric values whenEnumToEnumMapSettingisNumericValue, or by shared[Description]attribute values whenEnumStringMapSettingorEnumToEnumMapSettingisDescription; - When mapping enum β enum, if at least one source enum member cannot be paired with a target member (by name, numeric value, or Description, depending on
EnumToEnumMapSetting), the generator reports warning MP00039 and continues code generation; unmapped source values throwArgumentOutOfRangeExceptionat runtime; - When Description mapping is enabled, every enum member involved must have a non-empty
[Description]attribute; otherwise the generator reports error MP00040 and does not generate the mapping; - When Description mapping or case-insensitive member-name mapping would pair multiple source members with the same target member, the generator reports error MP00041 and does not generate the mapping;
- Enum β integral: maps enum members to their underlying integral values;
- Integral β enum: maps integral values (cast to the enum underlying type) to enum members;
- String β enum: maps string input to enum members by name or by
[Description]value (handled by the enum strategy, not the string strategy, because the enum detector runs first); whenCaseInsensitiveEnumMapis enabled inMappaSettings, member names or Description values are matched case-insensitively viaToUpperInvariant();
- Enum β enum and enum β string: a
- Notes:
- The enum detector runs before the general string strategy, so
stringβenumis handled here rather than by the string strategy; - Enum β enum matching uses member names by default; set
EnumToEnumMapSettingtoNumericValueto match by underlying numeric value, or toDescriptionto match by[Description]attribute value; - Enum β string matching uses member names by default; set
EnumStringMapSettingtoDescriptionto match by[Description]attribute value; - String β enum and enum β enum member-name matching is case-sensitive by default; enable
CaseInsensitiveEnumMapfor case-insensitive member name or Description matching.
- The enum detector runs before the general string strategy, so
5. String strategy
- When:
TSourceis astringandTTargetis any of the numeric types OR,TSourceis astringandTTargetis any of the following types:DateTime,DateTimeOffset,DateOnly,TimeOnly,TimeSpan,Guid,UriOR,TTargetis astringOR,TSourceis astringandTTargetis any type with an accessible staticParse(string)method;
- What:
TSourceis astringandTTargetis any of the numeric types: the relevantParsemethod is invoked, possibly with the culture and NumberStyles fromMappaSettings;- When parsing numeric types from
string, if a style is configured the generator emits the BCL overload that acceptsNumberStyles:Parse(input, style)when culture is not configured, orParse(input, style, culture)when culture is configured. The resolved style is the type-specificNumberStyleswhen set, otherwiseGlobalNumberStyle. When neither is configured, the overload withoutNumberStylesis used; TSourceis astringandTTargetisDateTime,DateTimeOffset,DateOnly,TimeOnly,TimeSpan, orGuid: the relevantParseorParseExactmethod is used, possibly with format, culture, and DateTimeStyles fromMappaSettings;- When parsing
DateTime,DateTimeOffset,DateOnly, orTimeOnlyfromstring, if a style is configured the generator emits the BCL overload that acceptsDateTimeStylesas the last parameter:Parse(input, culture, style)orParseExact(input, format, culture, style). The resolved style is the type-specificDateTimeStyleswhen set, otherwiseGlobalDateTimeStyle. When culture is not configured,nullis passed forIFormatProvider. When neither type-specific nor global style is configured, the overload withoutDateTimeStylesis used; - When a
DateTimeStylesorNumberStylesvalue from[MappaSettings]contains undefined bits (for example an arbitrary integer cast such as(DateTimeStyles)999), the generator reports warning MP00038 and continues code generation using only the recognized flag bits in the emitted parse call. Values from.editorconfigthat cannot be parsed are ignored without a diagnostic; TSourceis astringandTTargetisUri:System.UriBuilderis used;TTargetis astringandTSourceisDateTime,DateTimeOffset,DateOnly,TimeOnly,TimeSpan, orGuid: the relevantToString()overload is used, possibly with format and culture fromMappaSettings;TTargetis astringandTSourceis any numeric type: the relevantToStringoverload is used, possibly with format and culture fromMappaSettings;TTargetis astring:TSource.ToString()is used;TSourceis astringandTTargethas an accessible staticParse(string)method: theParsemethod is invoked;
- Notes:
stringβenumis handled by the enum strategy, not the string strategy;- When an accessible static
Parse(string)exists, the string/Parsestrategy runs before the constructor strategy; a single-string-parameter constructor does not take priority over staticParse.
6. Date & time strategy
- When:
TSourceis aDateTimeandTTargetislong,DateOnly, orTimeOnlyOR,TSourceis aDateTimeOffsetandTTargetislong,DateOnly,TimeOnly, orDateTimeOR,TSourceis aDateOnlyandTTargetislongorDateTimeOR,TSourceis alongor any smaller numeric type implicitly castable tolong, andTTargetisDateTimeorDateTimeOffsetOR,TSourceis aTimeSpanandTTargetisdoubleOR,TSourceis adoubleandTTargetisTimeSpan;
- What:
- The usual mapping conversions are used;
- When mapping from
DateOnlytoDateTime,TimeOnly.MinValueis combined withDateTimeKind.Utc; - When mapping to or from
long, Unix time is used; - When a timezone is required, UTC is implied;
- Notes:
DateTimeβDateTimeis handled by the identity strategy, not the date & time strategy;DateTimeβDateTimeOffsetis handled by the identity strategy;DateTimeOffsetβDateTimeis handled by the date & time strategy (not identity);- There is no dedicated
DateOnlyβDateTimeOffsetstrategy in the current implementation (onlyDateOnlyβDateTime).
7. Container strategy
- When:
TSourceandTTargetare both either dictionaries or collections,- For dictionaries, mappings exist from source key type to target key type and from source value type to target value type,
- For collections, a mapping exists from the source element type to the target element type,
TSourcedictionary types accepted:- any type implementing
IDictionary<TKey, TValue>; - any type implementing
IReadOnlyDictionary<TKey, TValue>; - any type implementing
IEnumerable<KeyValuePair<TKey, TValue>>;
- any type implementing
TTargetdictionary types accepted:- any type implementing
IDictionary<TKey, TValue>that has a constructor with zero arguments; - the following interfaces:
IDictionary<TKey, TValue>,IReadOnlyDictionary<TKey, TValue>,IImmutableDictionary<TKey, TValue>; - the following classes:
ImmutableDictionary<TKey, TValue>,ImmutableSortedDictionary<TKey, TValue>,FrozenDictionary<TKey, TValue>,ConcurrentDictionary<TKey, TValue>;
- any type implementing
TSourcecollection types accepted: any type implementingIEnumerable<T>, arrays,Span<T>,ReadOnlySpan<T>,Memory<T>, andReadOnlyMemory<T>;TTargetcollection types accepted:- any type implementing
ICollection<T>orISet<T>that has a constructor with zero arguments (or one constructor with one integer argument of typeintwhenMappaSettings.ContainerCapacityConstructorsis enabled); - any type derived from
Stack<T>,Queue<T>, orBlockingCollection<T>that has a constructor with zero arguments (or one constructor with one integer argument whenMappaSettings.ContainerCapacityConstructorsis enabled); - the following interfaces:
IEnumerable<T>,ICollection<T>,IReadOnlyCollection<T>,ISet<T>,IList<T>,IReadOnlyList<T>,IReadOnlySet<T>,IImmutableSet<T>,IImmutableList<T>,IImmutableQueue<T>,IImmutableStack<T>,IProducerConsumerCollection<T>; - the following classes: arrays,
List<T>,ReadOnlyCollection<T>,Span<T>,ReadOnlySpan<T>,Memory<T>,ReadOnlyMemory<T>,Stack<T>,Queue<T>,ReadOnlySet<T>,HashSet<T>,SortedSet<T>,FrozenSet<T>,ImmutableHashSet<T>,ImmutableSortedSet<T>,ImmutableArray<T>,ImmutableList<T>,ImmutableQueue<T>,ImmutableStack<T>,ConcurrentBag<T>,ConcurrentQueue<T>,ConcurrentStack<T>;
- any type implementing
- What:
- A
forloop orforeachloop is added to the code; - In the loop, each element from the source collection is mapped to an element of the target collection and then added to the target collection;
- A
- Notes:
- When possible for some types (e.g.
List<T>), the constructor accepting capacity is preferred to reduce allocations (ContainerCapacityConstructors); - When
MappaSettings.FastCollections(or the corresponding.editorconfigsetting) is enabled, collection mapping may use span-based iteration for array andList<T>sources and may allocate target arrays with a known capacity; - When
MappaSettings.EnumerableConcreteTypeisArray(or the corresponding.editorconfigsetting), sequence-like interface targets such asIEnumerable<T>,IList<T>,ICollection<T>,IReadOnlyList<T>, andIReadOnlyCollection<T>use aT[]buffer instead ofList<T>; concreteList<T>targets are unchanged; - Explicit interface implementation is supported;
- Types with an empty constructor are supported if they are derived from any of the supported interfaces or classes.
- When possible for some types (e.g.
8. Tuple strategy
- When:
TSourceandTTargetare both tuple types,- The number of elements in the tuple is the same,
- For each element of the tuple there exists a mapping from source element to target element;
- What:
- Each element of the source tuple is mapped into a new element of the target tuple;
- The target tuple is created by combining the mapped elements;
- Notes:
- Both named and unnamed tuples are supported;
- The type
Tuple<T>(and its variations with more elements) is supported.
9. Guid strategy
- When:
TSourceisGuidandTTargetisbyte[],Span<byte>,ReadOnlySpan<byte>,Memory<byte>, orReadOnlyMemory<byte>, ORTSourceisbyte[],Span<byte>,ReadOnlySpan<byte>,Memory<byte>, orReadOnlyMemory<byte>andTTargetisGuid;
- What:
- A mapping from
Guidtobyte[]/Span<byte>is defined using the relevantGuidconstructors or theGuid.ToByteArray()method.
- A mapping from
10. Constructor strategy
The constructor strategy has three sub-strategies, tried in order:
| Sub-strategy | When |
|---|---|
| Mapping constructor | An accessible constructor TTarget(TSource input) exists where the single parameter type matches the source type |
| Empty constructor + property init | An accessible zero-argument constructor exists; settable properties (and get-only collections per the notes below) can be mapped from the source |
| Parameterized constructor | No suitable empty-constructor path; the accessible constructor with the most mappable parameters is chosen (parameter names are matched to source properties case-insensitively by default) |
- What:
- Each property, constructor argument, or mapping-constructor parameter is mapped and a new instance of
TTargetis generated; - Get-only dictionary or collection properties for which a mapper exists are filled with mapped values from the corresponding source;
- Each property, constructor argument, or mapping-constructor parameter is mapped and a new instance of
- Notes:
- Empty-constructor path: property name matching is case-sensitive by default, configurable via
CaseInsensitivePropertyMapandIgnoreUnderscoreForPropertyMapinMappaSettings; - Parameterized-constructor path: constructor parameter names are matched to source properties case-insensitively by default, with optional underscore-insensitive matching via
IgnoreUnderscoreForPropertyMap; - Explicit interface implementation is supported for get-only dictionary and collection properties;
- Get-only
Stack<T>,Queue<T>,ConcurrentStack<T>,ConcurrentQueue<T>,ConcurrentBag<T>, andBlockingCollection<T>properties are filled post-construction usingPush,Enqueue, orAddrespectively; - The following attributes on the map method can override mapping behaviour (see
Documentation/mappa-attributes.mdfor details):[MappaUseProperty][MappaIgnoreTargetProperty](empty-constructor path only)[MappaAssignFromContext][MappaAssignFromConstant][MappaInvokeMethod]β optionally acceptsSourcePropertyNameto select the source property passed to the invoked method[MappaAssignToContext](post-construction context writes; requires the caller to provideMappaContext)
- When
MappaSettings.ProtobufOptionalis enabled, optional protobuf members are handled via companionHas*properties on the source and target types.
- Empty-constructor path: property name matching is case-sensitive by default, configurable via
Limitations
Currently unsupported features include:
- Generic type parameters on map methods (for example,
TTarget Map<TSource, TTarget>(TSource input)).
Other relevant packages:
- Mappa: attributes and
MappaContextused to drive the source generator; - Mappa Protobuf: methods to map
Google.Protobuf.WellKnownTypesobjects from Google.Protobuf package into common objects. - Mappa Protobuf dependency: utility methods to register the Protobuf mapper.
- Mappa Bson: methods to map
MongoDB.Bsonobjects from MongoDB.Bson package into common objects. - Mappa Bson dependency: utility methods to register the Bson mapper.
You can find samples here. Visit the Mappa documentation to learn more.
Learn more about Target Frameworks and .NET Standard.
-
.NETStandard 2.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.