Mappa 10.3.0
dotnet add package Mappa --version 10.3.0
NuGet\Install-Package Mappa -Version 10.3.0
<PackageReference Include="Mappa" Version="10.3.0" />
<PackageVersion Include="Mappa" Version="10.3.0" />
<PackageReference Include="Mappa" />
paket add Mappa --version 10.3.0
#r "nuget: Mappa, 10.3.0"
#:package Mappa@10.3.0
#addin nuget:?package=Mappa&version=10.3.0
#tool nuget:?package=Mappa&version=10.3.0
Mappa
This package contains all the attributes that can be used to drive the behaviour of the Mappa source generator. This is the list of attributes provided:
Mappa: Identifies partial classes that are meant to be source generated by the Mappa source generator;MappaInterceptor: Identifies partial non-static classes for which the Mappa source generator emits interceptable instanceMappaMap(or renamed) stubs and C# interceptor methods for inline mapping; may coexist withMappa; configure call sites withWith(...)(compile-time only;newarguments); list mapper namespaces inMappaInterceptorsNamespaces— see MappaInterceptor and the tutorial;MappaInterceptorMethodDependency: Marks a method that may be used as a mapping dependency on theMappaInterceptorpath only (ignored on theMappapath);MappaDependencyInjection: Identifies a partial registrar class for which the Mappa source generator emits a method that registers[Mappa]mapper types into anIServiceCollection(same assembly by default; optionally additional assemblies viaInjectFromAssemblies— see MappaDependencyInjection);MappaIgnore: Identifies methods that should not be used for mapping;MappaDependency: Identifies a property or field inside a mapper class that can be used when identifying suitable mappings between two types; fields and properties tagged on accessible base classes of the mapper are also considered; methods on the dependency type and its base classes are considered when the field or property type is that type or a derived type;MappaStaticDependency: Defines a static class whose methods can be used as dependencies while performing mappings;MappaSettings: Allows specifying mapping behaviour (for example, culture when parsing or formatting date/time,Guid, and numeric types, and format when converting numeric types tostring);MappaProjection: Opt-in/opt-out forIQueryable<TSource>→IQueryable<TTarget>deferred projection on a mapper class or map method (Enableddefaults toEnablewhen the attribute is present; signature-driven projection remains the default when the attribute is absent);MappaUseProperty: When mapping structured types (class,struct, and records) allows specifying which source property to use for a target property or constructor parameter;TargetPropertyNameandSourcePropertyNamemay be a single name or a dot-separated chain of nested property names (for example"Address.City");MappaIgnoreTargetProperty: When mapping structured types via an empty constructor, excludes a target property from property-initializer mapping; has no effect when mapping uses a constructor with parameters;TargetPropertyNamemay be a single name or a dot-separated chain of nested property names;MappaMustMapTargetProperty: When mapping structured types via an empty constructor (or empty-constructor-like factory), requires that listed non-required target properties—or all of them when no names are provided—are mapped; otherwise generation fails with MP00065;MappaAllowInaccessibleSourceMembers: Opt-in to read private/protected source properties (and fields whenMapSourceFieldsis enabled) via generatedUnsafeAccessormethods (flat names, or all when omitted); requires .NET 8+ / C# 12+;MappaAllowInaccessibleTargetMembers: Opt-in to write private/protected target properties/fields and/or invoke inaccessible target constructors via generatedUnsafeAccessormethods;AllowProperties/AllowFields/AllowConstructorscontrol each kind (defaultstrue); requires .NET 8+ / C# 12+;MappaAssignFromContext: When mapping structured types, allows specifying which value from aMappaContextto use for a target property or constructor parameter;TargetPropertyNamemay be a single name or a dot-separated chain of nested property names;MappaAssignToContext: When mapping structured types via the constructor-map strategy, stores the value of a target property or field inMappaContextafter the target object has been fully constructed;TargetPropertyNamemay be a single name or a dot-separated chain of nested member names;MappaInvokeMethodAttribute: When mapping structured types via the constructor-map strategy, forces a target property or constructor parameter to be mapped by invoking a named method; supports an optionalSourcePropertyNamenamed parameter to select the source property passed to the invoked method; bothTargetPropertyNameandSourcePropertyNamemay be a single name or a dot-separated chain of nested property names;MappaAssignFromConstant: When mapping structured types, allows specifying a constant value for a target property or constructor parameter;TargetPropertyNamemay be a single name or a dot-separated chain of nested property names;MappaNullSubstitute: When mapping structured types, substitutes a null source member with a constant (AssignValue) or a method call (InvokeMethod) before mapping continues; optionalSourcePropertyName;TargetPropertyNameandSourcePropertyNamemay be a single name or a dot-separated chain of nested property names;MappaBeforeMap: Invokes a named hook immediately before the generated root mapping body; applies to mapper classes and mapping methods;MappaAfterMap: Invokes a named hook immediately after the generated root mapping body and before returning the target; applies to mapper classes and mapping methods;MappaTransformer: Marks a method as a value transformer (T→T, optionally with aMappaContext) applied at every matching mapping site of the mapper class (source before mapping, mapped value before assignment/return); applies to methods;MappaApplyTransformer: Applies a named value transformer to a mapping method, optionally limited to a source property or dot-separated nested path; the method may be on the mapper, on astaticclass type, or on a mapper field/property (FieldName); may be repeated; not supported onIQueryableprojection methods;MappaObjectFactory: Forces construction of a target type via a named factory method instead ofnew; applies to mapper classes and mapping methods;MappaUseConstructor: Forces empty or parameterized constructor selection for the map method return type or a nested target type (ConstructorType.NoParameters/WithParameters, optional exact parameter types); also available asMappaUseConstructorAttribute<T1>…<T1, …, T8>for exact signatures (optionaltargetTypeargument for nested types);MappaSourcePreferredInterfaceImplementation: When a source type implements multiple closed versions of the same collection/dictionary interface family, forces which closed interface to use (method-only; exact match on implementing type and interface family); also available asMappaSourcePreferredInterfaceImplementation<TImplementingType, TClosedInterface>;MappaTargetPreferredInterfaceImplementation: Same preference for concrete multi-interface target types (method-only); mainly needed when element/key/value types andAdd/indexer access must be discovered via those interfaces; also available asMappaTargetPreferredInterfaceImplementation<TImplementingType, TClosedInterface>;MappaTypeMapping: When mapping structured types or interfaces, allows defining the target type depending on the source type; also available asMappaTypeMapping<TTarget, TSource>;MappaTypeMappingDefault: Describes the default behaviour for polymorphic methods defined viaMappaTypeMapping; also available asMappaTypeMappingDefault<TDefault>forMapSourceTypewith an explicit target type;MappaProtobufPolymorphismSetup: Identifies which protobufoneofcase property drives protobuf polymorphism on a map method (single-property or target+source forms);MappaProtobufTypeMapping: Defines one arm of a protobufoneofpolymorphism mapping (constructors for proto→POCO, POCO→proto, and proto→proto; no generics);MappaProtobufTypeMappingDefault: Describes the default behaviour for protobufoneofpolymorphism (Throw,NoMap,MapTo);MappaMapEnumMember: Configures explicit enum↔integral, enum↔string, or enum↔enum member pairings;MappaMapEnumIgnore: Excludes a specific enum member from mapping;MappaMapEnumDefault: Configures fallback behaviour when an enum value cannot be mapped;
Method-applicable mapper attributes (except MappaSettings) implement IMappaMethodAttribute so they can be passed to MappaInterceptorExtensions.With for interceptor call-site configuration. MappaSettings remains a dedicated With parameter.
This package also provides the MappaContext class that can be used to pass contextual values to mappers via the MappaAssignFromContext attribute, store mapped values via the MappaAssignToContext attribute, supply context to methods invoked via the MappaInvokeMethodAttribute attribute, supply context to before/after map hooks, or supply context to object factory methods. When ReferenceReusing or MaxRuntimeDepth is enabled, MappaContext also owns a private MappaReferenceManager used by generated code to track mapped references (keyed by source identity and typeof(TTarget)) and nesting depth. MappaContext is not thread-safe: use one instance per logical mapping operation and do not share a single instance across concurrent mappings without external synchronization.
Queryable projection: map methods with signature IQueryable<TSource> → IQueryable<TTarget> are handled by the generator as deferred Select projections for ORM providers. Projection is signature-driven by default; use [MappaProjection] on a class or method to opt in or out (Enabled = Disable skips the projection strategy). Generated projection methods are annotated with [RequiresDynamicCode] and are not compatible with Native AOT. See the tutorial and IQueryableProjectionMapper.cs.
Via MappaSettings the following settings can be tweaked:
DateTimeFormat: the format to use when mappingstrings to and fromSystem.DateTime;DateTimeOffsetFormat: the format to use when mappingstrings to and fromSystem.DateTimeOffset;DateOnlyFormat: the format to use when mappingstrings to and fromSystem.DateOnly;TimeOnlyFormat: the format to use when mappingstrings to and fromSystem.TimeOnly;DateTimeStyle: the DateTimeStyles to use when parsingstrings toSystem.DateTime(unset values inherit; does not affectToString);DateTimeOffsetStyle: the DateTimeStyles to use when parsingstrings toSystem.DateTimeOffset(unset values inherit; does not affectToString);DateOnlyStyle: the DateTimeStyles to use when parsingstrings toSystem.DateOnly(unset values inherit; does not affectToString);TimeOnlyStyle: the DateTimeStyles to use when parsingstrings toSystem.TimeOnly(unset values inherit; does not affectToString);GlobalDateTimeStyle: the default DateTimeStyles for parsing date/time types when the type-specific style is unset (type-specific styles override when both are set; does not affectToString);TimeSpanFormat: the format to use when mappingstrings to and fromSystem.TimeSpan;GuidFormat: the format to use when mappingstrings to and fromSystem.Guid;ByteFormat,SByteFormat,ShortFormat,UShortFormat,IntFormat,UIntFormat,LongFormat,ULongFormat,DecimalFormat,FloatFormat,DoubleFormat: the format to use when converting the corresponding numeric type tostring(numeric formats apply toToStringonly);ByteStyle,SByteStyle,ShortStyle,UShortStyle,IntStyle,UIntStyle,LongStyle,ULongStyle,DecimalStyle,FloatStyle,DoubleStyle: the NumberStyles to use when parsingstrings to the corresponding numeric type (unset values inherit; does not affectToString);GlobalNumberStyle: the default NumberStyles for parsing numeric types when the type-specific style is unset (type-specific styles override when both are set; does not affectToString);CultureInfoSetting: defines which culture to use when mapping any of the above types and numeric types (current culture, invariant culture, or user-defined culture);CultureName: defines the culture to use when user-defined culture is selected byCultureInfoSetting;ProtobufOptional: enables or disables the ability of the Mappa source generator to handleoptionalfields in protobuf models;BsonWellKnownTypes: whenEnable, mapsMongoDB.Bsonwell-known types (ObjectId↔string/byte[],Decimal128→decimal) inline (disabled by default; referenceMongoDB.Bson);ProtobufWellKnownTypes: whenEnable, mapsGoogle.Protobuf.WellKnownTypes(Timestamp,Duration, scalar wrappers) inline (disabled by default; referenceGoogle.Protobuf);OneOfWellKnownTypes: whenEnable, maps OneOf /OneOfBaseshapes (including OptionOneOf<T, None>) inline (disabled by default; referenceOneOf). Exact-armT → OneOf<…, T, …>via identity/implicit conversion remains available regardless of this setting;PragmaWarning: allows surrounding the generated methods with a#pragma warning disableblock;FastCollections: usesSpan<T>to make mappings involving arrays andSystem.Collections.Generic.List<T>faster;ReplaceNullWithEmptyContainer: when enabled, a null source collection or dictionary is mapped to an empty target container instead of producingnullor throwing (disabled by default);ContainerCapacityConstructors: supports mapping custom containers using (if available) a constructor accepting an integer value representing the initial capacity of the container;PreventEnumerableCount: when enabled, avoids callingEnumerable.Countwhen mapping from a source withoutCountorLengthto fixed-size targets such asT[],Span<T>,ReadOnlySpan<T>,Memory<T>, orReadOnlyMemory<T>; a growableList<T>buffer is used so the source is enumerated only once;EnumerableConcreteType: selects whether mappings to sequence-like collection interfaces (for exampleIEnumerable<T>) useList<T>(default) orT[]as the concrete buffer;DictionaryAssignment: selects whether dictionary mappings insert entries via the indexer (Indexer, default) orIDictionary<TKey,TValue>.Add(Add);PolymorphicMapMethodWithMatchingDefaultAttribute: when enabled,MappaTypeMappingDefaultcan be used to locate an appropriate polymorphic method when looking for the mapping between two types;CompatibleMapMethod: when enabled, nested existing-method reuse may invoke a map method whose parameter is a base type or interface of the required source and whose return type is a derived type of the required target (disabled by default);MappaTransformerFromDependency: when enabled,[MappaTransformer]methods declared on[MappaDependency]/[MappaStaticDependency]types are also applied as value transformers (disabled by default);CaseInsensitivePropertyMap: when enabled, source property (and field, when field mapping is enabled) names are matched case-insensitively when pairing a target member or constructor parameter with a source member by name;IgnoreUnderscoreForPropertyMap: when enabled, underscore characters are stripped from names before comparing a target member or constructor parameter with a source member by name;MapSourceFields: when enabled, accessible instance fields on the source type may be read when pairing with a target member or constructor parameter by name (disabled by default; property preferred when both match);MapTargetFields: when enabled, accessible instance fields on the target type may be written or initialized when pairing with a source member by name (disabled by default; property preferred when both match);MapSourceExplicitInterfaceProperties: when enabled, source properties that are explicitly implemented interface members may be read via a cast to the declaring interface (disabled by default);MapTargetExplicitInterfaceProperties: when enabled, target properties that are explicitly implemented interface members may be written via a cast to the declaring interface after construction (disabled by default);CaseInsensitiveEnumMap: when enabled, enum member names or[Description]values are matched case-insensitively when mapping between enums or fromstringto an enum;EnumStringMapSetting: selects whether enum and string mappings match members by name (default) or by[Description]attribute value;EnumToEnumMapSetting: selects whether enum-to-enum mappings match members by name (default), by underlying numeric value, or by[Description]attribute value;IdentityMapDeepCopy: selects whether identity mappings return the original reference, clone viaMemberwiseClone, or recursively copy nested fields (seeMappa.MappaCloning.MemberwiseClone).ReferenceReusing: when enabled, reuses already-mapped reference-type instances when the same source appears again (cycles / shared DAGs), keyed by source identity and declaredTTarget. RequiresMappaContext. Disabled by default.MaxRuntimeDepth: maximum runtime nesting depth (short; negative/-1= unset/inherit; effective default0= unlimited). RequiresMappaContext. Overflow throwsMappaException.MaxCompileTimeDepth: maximum generator strategy-discovery depth (short; negative/-1= unset/inherit; effective default50;0disables). Generator-only.BreakCompileTimeCycles: when enabled, synthesizes private map methods at compile-time mapping-cycle edges instead of MP00077; reports MP00078. Generator-only; disabled by default. Pair withReferenceReusingfor runtime object cycles.ProjectionEnumStringMapSetting: overridesEnumStringMapSettingfor enum↔string mappings insideIQueryableprojections (falls back toEnumStringMapSettingwhen unset);ProjectionEnumToEnumMapSetting: overridesEnumToEnumMapSettingfor enum↔enum mappings insideIQueryableprojections (falls back toEnumToEnumMapSettingwhen unset);ProjectionCaseInsensitiveEnumMap: overridesCaseInsensitiveEnumMapfor enum mappings insideIQueryableprojections (falls back toCaseInsensitiveEnumMapwhen unset);ProjectionGuidFormat: overridesGuidFormatforGuid↔stringmappings insideIQueryableprojections (falls back toGuidFormatwhen unset);ProjectionCultureInfoSetting: overridesCultureInfoSettingfor string parse/format insideIQueryableprojections (falls back toCultureInfoSettingwhen unset);ProjectionCultureName: overridesCultureNamewhenProjectionCultureInfoSettingis user-defined (falls back toCultureNamewhen unset).
Via MappaTypeMappingDefault the following settings can be tweaked:
Undefined: this setting should never be used;Throw: if the source type is not defined by any of theMappaTypeMappingattributes, throwsArgumentOutOfRangeExceptionor the exception defined in theMappaTypeMappingDefaultattribute;Default: returnsdefault;Null: returnsnull;MapSourceType: maps the source type to the target type of the method or the type specified in theMappaTypeMappingDefaultattribute;InvokeMethod: invokes a method in the mapper with the name specified inMappaTypeMappingDefaultto perform the mapping;MappaTypeMappingDefaultcan also specify the type on which the method is defined—in that case the method must bestatic. The method can optionally accept aMappaContextparameter.
Via MappaProtobufTypeMappingDefault / MappaProtobufTypeMappingDefaultBehavior the following settings can be tweaked:
Undefined: this setting should never be used;Throw: if no protobuf oneof arm matches (including source caseNone), throwsArgumentOutOfRangeExceptionor the exception defined in the attribute (default when the attribute is missing);NoMap: leave the target oneof unset (None); only valid when the target is a protobuf message;MapTo: map the unmatched source into a specific target oneof arm's message type; only valid when the target is a protobuf message.
Protobuf oneof polymorphism supports message-typed arms only. All constructors use the (target, source) order:
- proto → POCO:
[MappaProtobufPolymorphismSetup("ResultCase")]+[MappaProtobufTypeMapping(typeof(TTarget), "Ok")]; - POCO → proto:
[MappaProtobufPolymorphismSetup("ResultCase")]+[MappaProtobufTypeMapping("Ok", typeof(TSource))]; - proto → proto:
[MappaProtobufPolymorphismSetup("TargetCase", "SourceCase")]+[MappaProtobufTypeMapping("TargetOk", "SourceOk")].
The protobuf attributes cannot be combined with MappaTypeMapping / MappaTypeMappingDefault on the same method. See the Mappa attributes documentation for details.
Via MappaMapEnumDefaultBehavior the following settings can be tweaked:
Throw: throwsArgumentOutOfRangeExceptionwhen an enum value cannot be mapped (default);UseDefaultValue: returns the default value provided via[MappaMapEnumDefault]when an enum value cannot be mapped.
Relevant packages:
- Mappa source generator: source generator that automatically generates mappings between classes and value types.
For Bson/Protobuf/OneOf well-known types, enable BsonWellKnownTypes / ProtobufWellKnownTypes / OneOfWellKnownTypes and reference MongoDB.Bson, Google.Protobuf, or OneOf as needed.
You can find samples here. Visit the Mappa documentation to learn more.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- No dependencies.
NuGet packages (4)
Showing the top 4 NuGet packages that depend on Mappa:
| Package | Downloads |
|---|---|
|
Mappa.Dependency.Protobuf
Protobuf mapping method for common types. |
|
|
Mappa.Dependency.Bson
Helper methods to map some Bson types. |
|
|
Mappa.Dependency.Bson.DependencyInjection
Dependency injection for Bson mapping methods for common types. |
|
|
Mappa.Dependency.Protobuf.DependencyInjection
Dependency injection for Protobuf mapping for common types. |
GitHub repositories
This package is not used by any popular GitHub repositories.