Source of Truth: Canonical documentation generated from public symbols exported in
PublicAPI.Shipped.txt(EricksonLopez.Mapper.Abstractions),EricksonLopez.Mapper.DomainPrimitives,EricksonLopez.Mapper.Result,EricksonLopez.Mapper.Mapster, and Roslyn generator emitted code (EricksonLopez.Mapper.Generator).
Style: Formal Microsoft Learn-grade technical specification.
- Core Abstractions and Attributes (
EricksonLopez.Mapper.Abstractions)MapperAttributeMapPropertyAttributeMapIgnoreAttributeMapIgnoreSourceAttributeMapperIgnoreAttributeMapValueAttributeEnumMappingStrategyAttributeandEnumMappingStrategyMapEnumValueAttributeMapperDefaultsAttributeMapFactoryAttributeMapDerivedTypeAttributeUseConverterAttributeMapNullFallbackAttributeGenerateMapperRegistrationAttributeValueObjectAttribute
- Core Interfaces
- Extension Package:
EricksonLopez.Mapper.DomainPrimitives - Extension Package:
EricksonLopez.Mapper.Result - Extension Package:
EricksonLopez.Mapper.Mapster - Generator-Emitted Extension Methods
- Compilation Diagnostics Catalog (ELM001–ELM016)
Instructs the Roslyn Incremental Source Generator to implement partial methods declared on the annotated class or interface.
- Signature:
public sealed class MapperAttribute : Attribute - Constructor:
public MapperAttribute() - Properties:
public bool StrictMapping { get; set; } = true; - Remarks: When
StrictMapping = true, any destination property lacking a matching source member or explicit mapping rule triggers compilation errorELM001. - Basic Example:
[Mapper] public partial class UserMapper { public partial UserDto Map(User source); }
- Advanced Example:
[Mapper(StrictMapping = false)] public partial class LegacyMapper { public partial PartialDto Map(RichEntity source); }
- Best Practices: Keep
StrictMapping = trueon all new code to prevent accidental contract desynchronization. - Performance: Zero runtime cost. All processing executes at compile time.
- Common Mistakes: Omitting the
partialmodifier on the mapper class (ELM012). - When to Use: On any class declaring mapping methods generated by the library.
- When NOT to Use: On purely manual helper classes or external utility methods.
Configures explicit member pairing between a source property and a destination property when names differ or when flattening nested paths.
- Signature:
public sealed class MapPropertyAttribute : Attribute - Parameters:
string sourceName,string destinationName - Remarks: Supports deep dot-separated navigation paths (
"Customer.Address.City"). - Basic Example:
[MapProperty("InternalId", "CustomerId")] public partial CustomerDto Map(Customer source);
- Advanced Example:
[MapProperty("Customer.Address.City", "City")] public partial OrderSummaryDto Map(Order source);
- Best Practices: Prefer
nameof(...)for single-level member names over string literals. - Performance: Direct C# member assignment without overhead.
- Common Mistakes: Inverting parameter order (
destinationNamefirst instead ofsourceName). - When to Use: When models use distinct naming conventions or when flattening nested hierarchical properties.
- When NOT to Use: When properties share identical names and compatible types (convention matches automatically).
Explicitly excludes a destination property from mapping, suppressing ELM001 in strict mode.
- Signature:
public sealed class MapIgnoreAttribute : Attribute - Parameters:
string destinationName - Remarks: Placed on the mapping method.
- Basic Example:
[MapIgnore("InternalToken")] public partial UserDto Map(User source);
- Advanced Example:
[MapIgnore(nameof(OrderDto.ComputedScore))] [MapIgnore(nameof(OrderDto.AuditedBy))] public partial OrderDto Map(Order source);
- Best Practices: Document why the destination property is left unmapped or uninitialized.
- Performance: Zero cost; suppresses assignment code generation entirely.
- Common Mistakes: Supplying a source property name instead of the destination property name.
- When to Use: For destination properties computed post-mapping or intended strictly for internal use.
- When NOT to Use: To ignore sensitive source properties (use
[MapIgnoreSource]).
Explicitly excludes a source property from member resolution.
- Signature:
public sealed class MapIgnoreSourceAttribute : Attribute - Parameters:
string sourceName - Remarks: Ensures sensitive source properties cannot be accidentally mapped to destination members with matching names.
- Basic Example:
[MapIgnoreSource("PasswordHash")] public partial UserDto Map(UserEntity source);
- Advanced Example:
[MapIgnoreSource(nameof(UserEntity.PasswordHash))] [MapIgnoreSource(nameof(UserEntity.SecurityStamp))] public partial PublicUserDto Map(UserEntity source);
- Best Practices: Apply to mappers projecting domain entities onto public DTOs.
- Performance: Zero runtime cost.
- Common Mistakes: Confusing with
[MapIgnore]. - When to Use: On security or persistence entities to seal confidential fields.
- When NOT to Use: On destination DTOs.
Globally and permanently excludes a property or field from participating in any mapping across the entire solution.
- Signature:
public sealed class MapperIgnoreAttribute : Attribute - Constructor:
public MapperIgnoreAttribute() - Target:
AttributeTargets.Property | AttributeTargets.Field - Remarks: Placed directly on the member in the model definition.
- Basic Example:
public class Entity { public Guid Id { get; set; } [MapperIgnore] public string CacheToken { get; set; } }
- Best Practices: Use for ORM transient state, change trackers, or in-memory cache tokens.
- When to Use: For model members that must never participate in projections.
- When NOT to Use: For conditional exclusions that depend on specific mapping methods.
Injects a literal or computed C# expression directly into a destination property or parameter.
- Signature:
public sealed class MapValueAttribute : Attribute - Parameters:
string destinationName,string valueExpression - Remarks: The expression must be valid C# syntax in the scope of the generated method.
- Basic Example:
[MapValue("Status", "\"ACTIVE\"")] public partial AccountDto Map(Request source);
- Advanced Example:
[MapValue(nameof(AuditDto.ProcessedAt), "System.DateTime.UtcNow")] public partial AuditDto Map(Request source);
- Best Practices: Properly escape quotation marks for string literals (
"\"VALUE\""). - Common Mistakes: Omitting namespace qualifiers on static types (
DateTime.UtcNowwithoutSystem.). - When to Use: To bind constants, UTC timestamps, or environment metadata.
- When NOT to Use: For complex domain calculations requiring external service injection.
Controls whether the generator matches enum members by identifier name (ByName) or integral value (ByValue), and configures case sensitivity.
- Signature:
public sealed class EnumMappingStrategyAttribute : Attribute - Constructor:
public EnumMappingStrategyAttribute(EnumMappingStrategy strategy) - Property:
public bool IgnoreCase { get; set; } - Enum:
public enum EnumMappingStrategy { ByName = 0, ByValue = 1 }
- Basic Example:
[EnumMappingStrategy(EnumMappingStrategy.ByName, IgnoreCase = true)] public partial DestStatus Map(SourceStatus source);
- Advanced Example:
[EnumMappingStrategy(EnumMappingStrategy.ByValue)] public partial ExternalCode Map(InternalCode source);
- Best Practices: Use
ByNamewithIgnoreCase = truefor JSON / HTTP external integrations. - Common Mistakes: Using
ByValuewhen integer values represent distinct meanings across tiers.
Explicitly pairs enum members with disparate identifier names.
- Signature:
public sealed class MapEnumValueAttribute : Attribute - Parameters:
object source,object target - Basic Example:
[MapEnumValue(PaymentStatus.Pending, OrderStatus.Queued)] public partial OrderStatus Map(PaymentStatus source);
- Best Practices: Cover all valid states of the source enum to avoid unmapped cases in strict mode.
- When to Use: When enum member names do not match across architectural boundaries.
Defines assembly-level conventions for all mappers within the compilation.
- Signature:
public sealed class MapperDefaultsAttribute : Attribute - Properties:
StrictMapping { get; set; },EnumMappingStrategy { get; set; },EnumIgnoreCase { get; set; } - Target:
AttributeTargets.Assembly - Basic Example:
[assembly: MapperDefaults(StrictMapping = true, EnumMappingStrategy = EnumMappingStrategy.ByName, EnumIgnoreCase = true)]
- Best Practices: Declare in
AssemblyConfig.cs.
Instantiates the destination type by calling a static factory method instead of public constructors.
- Signature:
public sealed class MapFactoryAttribute : Attribute - Parameters:
string methodName - Basic Example:
[MapFactory("Create")] public partial Money Map(MoneyDto source);
- Best Practices: Use with Value Objects and DDD domain entities that validate invariants during instantiation.
- Common Mistakes: Declaring the factory method as private or instance-scoped (
ELM002).
Enables compile-time polymorphic dispatch using pattern matching switch expressions.
- Signature:
public sealed class MapDerivedTypeAttribute : Attribute - Parameters:
Type sourceType,Type targetType - Basic Example:
[MapDerivedType(typeof(Car), typeof(CarDto))] [MapDerivedType(typeof(Truck), typeof(TruckDto))] public partial VehicleDto Map(Vehicle source);
- Best Practices: Declare specific sub-mapping methods for each derived type (
MapCar,MapTruck). - Performance: Zero reflection; RyuJIT emits optimized direct jumps.
Delegates mapping logic to an IConverter<TSource, TDestination> specified by type or injected field name.
- Signature:
public sealed class UseConverterAttribute : Attribute - Constructors:
UseConverterAttribute(Type converterType),UseConverterAttribute(string converterFieldName) - Type-Based Example:
[UseConverter(typeof(AddressConverter))] public partial AddressDto Map(Address source);
- Field-Based Example:
[UseConverter(nameof(_converter))] public partial UserDto Map(LegacyUser source);
- Best Practices: Use the field constructor when the converter requires dependencies from IoC.
Emits a literal fallback expression when a nullable value type member evaluates to null.
- Signature:
public sealed class MapNullFallbackAttribute : Attribute - Parameters:
string destinationName,string fallbackExpression - Basic Example:
[MapNullFallback("Price", "0.0m")] public partial ProductDto Map(Product source);
- Best Practices: Use exact, typed C# literals.
Instructs the generator to emit AddGeneratedMappers(this IServiceCollection) for the assembly.
- Signature:
public sealed class GenerateMapperRegistrationAttribute : Attribute - Target:
AttributeTargets.Assembly - Basic Example:
[assembly: GenerateMapperRegistration]
Marks a class or struct as a Domain Value Object, allowing the generator to automatically wrap and unwrap its inner .Value property.
- Signature:
public sealed class ValueObjectAttribute : Attribute - Target:
AttributeTargets.Class | AttributeTargets.Struct - Basic Example:
[ValueObject] public readonly record struct CustomerId(Guid Value);
- Signature:
TDestination Convert(TSource source); - Parameters:
TSource source: Input object to transform. - Return:
TDestination: Transformed instance. - Exceptions: As defined by conversion logic (e.g.,
FormatException,ArgumentNullException). - Remarks: Serves as the canonical decoupled transformation contract across the ecosystem.
- Basic Example:
public class StringToIntConverter : IConverter<string, int> { public int Convert(string source) => int.Parse(source); }
- Advanced Example:
public class LocalizedDateConverter : IConverter<DateTime, string> { private readonly CultureInfo _culture; public LocalizedDateConverter(CultureInfo culture) => _culture = culture; public string Convert(DateTime source) => source.ToString("d", _culture); }
- Best Practices: Keep converter implementations pure, stateless, and non-blocking.
- Performance: Direct interface call compatible with JIT devirtualization.
- Common Mistakes: Throwing undocumented generic exceptions.
- When to Use: For conversions that cannot be inferred automatically by naming conventions.
- When NOT to Use: For straightforward member-to-member mappings with identical names and types.
Extracts the underlying scalar .Value from an IDomainPrimitive.
-
Signature:
public TValue Convert(TPrimitive source) -
Parameters:
TPrimitive source: Domain primitive instance. -
Return:
TValue: Extracted scalar primitive value. -
Exceptions:
ArgumentNullExceptionifsourceis null. -
Remarks: Zero-allocation; optimized for Domain
$\rightarrow$ Persistence / DTO boundaries. -
Example:
var converter = new DomainPrimitiveToValueConverter<EmailAddress, string>(); string email = converter.Convert(domainEmail);
- When to Use: When persisting or serializing domain primitives to databases or JSON.
-
When NOT to Use: If the type does not implement
IDomainPrimitive<TSelf, TValue>.
Extracts the scalar .Value from a strongly typed identifier IStrongId.
- Signature:
public TValue Convert(TStrongId source) - Parameters:
TStrongId source: Strongly typed ID instance. - Return:
TValue: Primitive identifier (Guid,int,long, etc.). - Exceptions: None for structs (
readonly record struct). - Example:
var converter = new StrongIdToValueConverter<CustomerId, Guid>(); Guid rawId = converter.Convert(customerId);
- When to Use: Unpacking DDD identity wrappers before writing to databases (e.g., PostgreSQL / Dapper).
Rehydrates an IDomainPrimitive instance by invoking the static factory method TPrimitive.Create(value).
- Signature:
public TPrimitive Convert(TValue source) - Parameters:
TValue source: Scalar value from database or external request. - Return:
TPrimitive: Validated domain primitive instance. - Exceptions: Business validation exceptions defined in
Createif the scalar input is invalid. - Remarks: Requires .NET 7+ static abstract interface members.
- Example:
var converter = new ValueToDomainPrimitiveConverter<string, EmailAddress>(); EmailAddress email = converter.Convert("valid@example.com");
- When to Use: Hydrating rich domain models from persistence or HTTP input contracts.
Synchronously projects the success value of a Result<T>.
- Signature:
public static Result<TDest> Map<TSource, TDest>( this Result<TSource> result, Func<TSource, TDest> mapFunc);
- Parameters:
this Result<TSource> result: Source result instance.Func<TSource, TDest> mapFunc: Transformation delegate (typicallymapper.Map).
- Return:
Result<TDest>containing the projected value if successful, or the originalErrorif failed. - Exceptions:
ArgumentNullExceptionifmapFuncis null. - Remarks: If
result.IsFailureis true,mapFuncnever executes, short-circuiting efficiently. - Example:
Result<UserEntity> entityResult = repository.GetById(id); Result<UserDto> dtoResult = entityResult.Map(userMapper.Map);
- Performance: Zero additional heap allocation over the underlying result structure.
Asynchronously projects the success value of an operation returning Task<Result<T>>.
- Signature:
public static async Task<Result<TDest>> MapAsync<TSource, TDest>( this Task<Result<TSource>> resultTask, Func<TSource, TDest> mapFunc);
- Parameters:
this Task<Result<TSource>> resultTask: Asynchronous task returning a result.Func<TSource, TDest> mapFunc: Transformation delegate.
- Return:
Task<Result<TDest>>. - Exceptions:
ArgumentNullExceptionifresultTaskormapFuncis null. - Remarks: Uses
.ConfigureAwait(false)internally for optimal thread dispatch.
Asynchronously projects the success value of an operation returning ValueTask<Result<T>>.
- Signature:
public static async ValueTask<Result<TDest>> MapAsync<TSource, TDest>( this ValueTask<Result<TSource>> resultTask, Func<TSource, TDest> mapFunc);
- Parameters:
this ValueTask<Result<TSource>> resultTask: Structured ValueTask returning a result.Func<TSource, TDest> mapFunc: Transformation delegate.
- Return:
ValueTask<Result<TDest>>. - Exceptions:
ArgumentNullExceptionifmapFuncis null. - Remarks: Ideal for high-throughput cached read paths where the task completes synchronously, eliminating heap allocation.
Projects an enumerable contained in a Result<IEnumerable<TSource>> into an immutable Result<IReadOnlyList<TDest>>.
- Signature:
public static Result<IReadOnlyList<TDest>> MapList<TSource, TDest>( this Result<IEnumerable<TSource>> result, Func<TSource, TDest> mapFunc);
- Parameters:
this Result<IEnumerable<TSource>> result: Source result containing an enumerable.Func<TSource, TDest> mapFunc: Per-element transformation delegate.
- Return:
Result<IReadOnlyList<TDest>>with the projected read-only list.
- Constructors:
public MapsterConverter(): Uses global configurationTypeAdapterConfig.GlobalSettings.public MapsterConverter(TypeAdapterConfig config): Uses an isolated, dedicated configuration instance.
- Remarks: Encapsulates Mapster execution behind the standard
IConverter<TSource, TDestination>interface.
- Signature:
public TDestination Convert(TSource source); - Parameters:
TSource source: Input object. - Return:
TDestination: Produced target object.
Registers an IConverter<TSource, TDestination> within Mapster's configuration engine.
- Signature:
public static TypeAdapterConfig UseConverter<TSource, TDestination>( this TypeAdapterConfig config, IConverter<TSource, TDestination> converter);
- Parameters:
this TypeAdapterConfig config: Mapster configuration instance.IConverter<TSource, TDestination> converter:EricksonLopez.Mapperconverter.
- Return: The same
TypeAdapterConfiginstance for fluent chaining.
Automatically registers all non-static mappers and referenced converters into IServiceCollection.
-
Signature:
public static IServiceCollection AddGeneratedMappers(this IServiceCollection services); -
Namespace:
EricksonLopez.Mapper -
Requirement: Declare
[assembly: GenerateMapperRegistration]. -
Service Lifetimes:
- Non-static
[Mapper]classes$\rightarrow$ Singleton. - Type converters
$\rightarrow$ Transient. -
static partial classmappers$\rightarrow$ Omitted (require no instance).
- Non-static
| Code | Severity | Description | Recommended Solution |
|---|---|---|---|
| ELM001 | Error | Destination property unmapped in strict mode | Add [MapProperty], [MapIgnore], or [MapValue] |
| ELM002 | Error | Destination type lacks accessible constructor or factory method | Add public constructor or [MapFactory] |
| ELM003 | Error | Incompatible type conversion | Ensure types are compatible or use [UseConverter] |
| ELM004 | Error | Nullability mismatch (source nullable, destination non-nullable) | Apply [MapNullFallback] |
| ELM005 | Error | Ambiguous property matching | Disambiguate with explicit [MapProperty] |
| ELM006 | Error | Missing accessible setters or init-only properties on destination | Add property setters or compatible constructor |
| ELM007 | Error | Ambiguous constructor on destination | Specify factory using [MapFactory] |
| ELM008 | Error | Prohibited use of reflection in mapper | Remove calls to System.Reflection |
| ELM009 | Error | Prohibited use of dynamic keyword |
Use statically typed members |
| ELM010 | Error | Circular dependency detected between types | Break circular references in DTO models |
| ELM011 | Warning | Abstract base type with potentially uncovered derived variants | Cover all derived types using [MapDerivedType] |
| ELM012 | Error | [Mapper] class is not declared as partial |
Add the partial modifier |
| ELM013 | Error | Converter specified in [UseConverter] does not implement IConverter |
Implement IConverter<TSource, TDestination> |
| ELM014 | Error | Unmapped enum member in strict mode | Remap using [MapEnumValue] |
| ELM015 | Warning | Narrowing numeric conversion with risk of data loss | Use same-width types or explicit converter |
| ELM016 | Warning | String-to-enum parsing with risk of runtime exception | Validate strings or use strongly typed enums |
| ELM017 | Error | Factory method specified in [MapFactory] not found on destination type |
Verify factory method name and accessibility |
| ELM018 | Warning | Duplicate [MapProperty] targeting the same destination member |
Remove redundant attribute declaration |