Pitasoft.ObjectMapping
1.1.1
dotnet add package Pitasoft.ObjectMapping --version 1.1.1
NuGet\Install-Package Pitasoft.ObjectMapping -Version 1.1.1
<PackageReference Include="Pitasoft.ObjectMapping" Version="1.1.1" />
<PackageVersion Include="Pitasoft.ObjectMapping" Version="1.1.1" />
<PackageReference Include="Pitasoft.ObjectMapping" />
paket add Pitasoft.ObjectMapping --version 1.1.1
#r "nuget: Pitasoft.ObjectMapping, 1.1.1"
#:package Pitasoft.ObjectMapping@1.1.1
#addin nuget:?package=Pitasoft.ObjectMapping&version=1.1.1
#tool nuget:?package=Pitasoft.ObjectMapping&version=1.1.1
Pitasoft.ObjectMapping
English
Pitasoft.ObjectMapping is a high-performance .NET object mapper for backend scenarios.
It is designed for:
Entity -> DTODTO -> Entity- partial updates over existing tracked entities
- flattening nested source contracts into flat DTOs
- repeated high-volume mapping in APIs and services
- runtime diagnostics, validation, and startup precompilation
Installation
dotnet add package Pitasoft.ObjectMapping
Companion packages live in separate repositories:
dotnet add package Pitasoft.ObjectMapping.DependencyInjectionExtensions
dotnet add package Pitasoft.ObjectMapping.Generator
What this package includes
- convention-based mapping
- attribute-based mapping with
MapFrom,MapFromPath, andMapIgnore - fluent configuration with profiles
MapIntofor updating existing targets- selected-member mapping
- collection mapping
- safe
TryMap*APIs - constructor-aware mapping
- validation and structured diagnostics
- runtime descriptor APIs for tooling
- startup precompilation
IQueryableprojection support for projectable rules
Core API
| Area | API |
|---|---|
| Create a new destination | MapTo<TSource, TTarget>(), MapToValue<TSource, TTarget>() |
| Update an existing destination | MapInto<TSource, TTarget>() |
| Selected members | MapMembersTo, MapMembersInto, expression overloads |
| Collections | MapListTo, MapReadOnlyListTo, MapArrayTo |
| Safe APIs | TryMapTo, TryMapInto, TryMapListTo, TryMapReadOnlyListTo, TryMapArrayTo |
| Attributes | MapFrom, MapFromPath, MapIgnore |
| Fluent configuration | ObjectMappingConfiguration, CreateMap, ToMember, FromMember, FromPath, FromSource, When, Ignore |
| Profiles | ObjectMappingProfile, IObjectMappingProfile, AddProfile, AddProfilesFromAssemblies |
| Converters | AddConverter, member-specific converters, profile-scoped converters |
| Validation | Validate, ValidateMap, ValidateConventionMap, GetValidationErrors, GetValidationErrors<TSource, TTarget>, GetConventionValidationError |
| Diagnostics | GetRegisteredMaps, GetMapDescriptors, GetMapDescriptor, TryGetMapDescriptor, GetConventionMapDescriptor, TryGetConventionMapDescriptor, GetEffectiveMapDescriptor, TryGetEffectiveMapDescriptor |
| Precompilation | CompileMaps, CompileMaps(Predicate<...>), CompileMapsForProfile, CompileMapsFromAssembly, CompileMap, CompileConventionMap |
| Hooks | BeforeMap, AfterMap, MapUsing, MapIntoUsing |
| Projection | BuildProjectionExpression, ProjectTo |
| Service facade | IObjectMapper, ObjectMapper |
Which option should I use?
| Scenario | Recommended option |
|---|---|
| source and target mostly match by name | convention-based MapTo or MapInto |
| one or two renamed members | attributes |
| application-level mapping contract | fluent configuration |
| large module with many related maps | profile |
update DTO should keep existing values for null members |
MapInto with IgnoreNullValues = true |
| startup cost is acceptable and first-hit latency matters | Validate() plus CompileMaps*() |
| mapping needs business logic | MapUsing, MapIntoUsing, BeforeMap, AfterMap |
| you need runtime inspection | descriptors (GetMapDescriptor, GetConventionMapDescriptor, GetEffectiveMapDescriptor) |
| you need EF Core style projection | ProjectTo, but only for projectable rules |
Resolution order
Destination members are resolved in this order:
- fluent configuration
MapFromAttributeMapFromPathAttribute- direct member-name match
- convention options such as case-insensitive matching and prefix stripping
- convention flattening when applicable
General rules:
- source members must be readable
- destination members must be writable, unless constructor mapping is used
- nested paths are only used when configured or attributed
- converters are required when types do not match and no built-in conversion exists
- delegates are compiled and cached
Quick start
End-to-end example: Entity -> DTO -> Update DTO -> Entity
using Pitasoft.ObjectMapping;
using Pitasoft.ObjectMapping.Configuration;
public sealed class CustomerEntity
{
public Guid Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public AddressEntity Address { get; set; } = new();
public DateTime CreatedAtUtc { get; set; }
public DateTime UpdatedAtUtc { get; set; }
}
public sealed class AddressEntity
{
public string City { get; set; } = string.Empty;
}
public sealed class CustomerDto
{
public Guid Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public string? City { get; set; }
}
public sealed class UpdateCustomerDto
{
public string? Name { get; set; }
public string? Email { get; set; }
}
var configuration = new ObjectMappingConfiguration()
.ConfigureOptions(options =>
{
options.IgnoreNullValues = true;
});
configuration.UseAuditableMemberStrategy(ObjectMappingAuditableMemberStrategy.IgnoreCommonMembers);
configuration.CreateMap<CustomerEntity, CustomerDto>()
.ToMember(target => target.City).FromPath(source => source.Address.City);
var entity = new CustomerEntity
{
Id = Guid.NewGuid(),
Name = "Ada Lovelace",
Email = "ada@example.com",
Address = new AddressEntity { City = "London" },
CreatedAtUtc = DateTime.UtcNow,
UpdatedAtUtc = DateTime.UtcNow
};
var dto = entity.MapTo<CustomerEntity, CustomerDto>(configuration);
var updateDto = new UpdateCustomerDto
{
Name = "Ada Byron",
Email = null
};
updateDto.MapInto(entity, configuration);
What happens:
MapTocreates a newCustomerDtoFromPath(...)flattensAddress.CityintoCityMapIntoupdates the tracked entity instanceIgnoreNullValues = truekeeps the oldEmail- the auditable strategy avoids common audit member updates
Usage examples
1. Convention-based mapping
using Pitasoft.ObjectMapping;
public sealed class UserEntity
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
}
public sealed class UserDto
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
}
var dto = entity.MapTo<UserEntity, UserDto>();
2. Mapping into an existing destination
var dto = new UserDto();
entity.MapInto(dto);
3. Mapping only selected members
var dto = entity.MapMembersTo<UserEntity, UserDto>("Id", "Name");
var existing = new UserDto { Id = 1, Name = "Old", Email = "old@example.com" };
entity.MapMembersInto(existing, "Name");
Expression overloads:
var dto = entity.MapMembersTo<UserEntity, UserDto>(
target => target.Id,
target => target.Name);
entity.MapMembersInto(existing,
target => target.Name,
target => target.Email);
4. Collection mapping
var list = users.MapListTo<UserEntity, UserDto>();
var readOnly = users.MapReadOnlyListTo<UserEntity, UserDto>();
var array = users.MapArrayTo<UserEntity, UserDto>();
With configuration:
var configuration = new ObjectMappingConfiguration();
configuration.CreateMap<UserEntity, UserDto>()
.ToMember(target => target.DisplayName)
.FromMember(source => source.Name);
var list = users.MapListTo<UserEntity, UserDto>(configuration);
5. Safe mapping with TryMap*
if (entity.TryMapTo<UserEntity, UserDto>(out var dto))
{
// dto is available
}
var target = new UserDto();
if (!entity.TryMapInto(target))
{
// mapping failed
}
TryMapInto is best-effort safe for top-level writable members. It does not promise deep transactional rollback of arbitrary nested graphs.
6. Attribute-based mapping
using Pitasoft.ObjectMapping.Attributes;
public sealed class OrderEntity
{
public string Number { get; set; } = string.Empty;
public CustomerEntity Customer { get; set; } = new();
}
public sealed class OrderDto
{
[MapFrom(nameof(OrderEntity.Number))]
public string OrderNumber { get; set; } = string.Empty;
[MapFromPath("Customer.Name")]
public string CustomerName { get; set; } = string.Empty;
[MapIgnore]
public string InternalNotes { get; set; } = string.Empty;
}
7. Fluent member rename
var configuration = new ObjectMappingConfiguration();
configuration.CreateMap<UserEntity, UserDto>()
.ToMember(target => target.DisplayName)
.FromMember(source => source.Name);
8. Fluent nested path
configuration.CreateMap<OrderEntity, OrderDto>()
.ToMember(target => target.CustomerCity)
.FromPath(source => source.Customer.Address.City);
9. Ignore a destination member
configuration.CreateMap<UserEntity, UserDto>()
.ToMember(target => target.InternalCode)
.Ignore();
10. Compute a destination member from the full source
configuration.CreateMap<UserEntity, UserSummaryDto>()
.ToMember(target => target.DisplayLabel)
.FromSource(source => $"{source.Name} <{source.Email}>");
11. Conditional mapping with When(...)
configuration.CreateMap<UserPatchDto, UserEntity>()
.ToMember(target => target.Email)
.When(source => !string.IsNullOrWhiteSpace(source.Email))
.FromMember(source => source.Email!);
12. Global and member-specific converters
configuration.AddConverter<string, Guid>(value => Guid.Parse(value));
configuration.CreateMap<CreateOrderDto, OrderEntity>()
.ToMember(target => target.CustomerId)
.FromMember(source => source.CustomerIdText);
Member-specific converter:
configuration.CreateMap<SourceModel, TargetModel>()
.ToMember(target => target.Amount)
.FromMember<decimal, decimal>(source => source.Amount, value => decimal.Round(value, 2));
13. Before and after callbacks
configuration.CreateMap<CreateUserDto, UserEntity>()
.BeforeMap((source, target) => target.CreatedAtUtc = DateTime.UtcNow)
.AfterMap((source, target) => target.NormalizedEmail = target.Email.ToUpperInvariant());
14. Manual mapping hooks
configuration.CreateMap<LegacyUserRow, UserEntity>()
.MapUsing(source => new UserEntity
{
Id = source.UserId,
Name = source.FullName,
Email = source.Mail
});
configuration.CreateMap<UpdateInventoryDto, InventoryItem>()
.MapIntoUsing((source, target) =>
{
target.Quantity += source.QuantityDelta;
target.UpdatedAtUtc = DateTime.UtcNow;
});
Manual maps are opaque for effective runtime descriptors. The descriptor keeps map metadata, but its member list is not treated as authoritative.
15. Profiles
using Pitasoft.ObjectMapping.Configuration;
public sealed class SalesProfile : ObjectMappingProfile
{
public override void Configure(ObjectMappingConfiguration configuration)
{
configuration.CreateMap<OrderEntity, OrderDto>()
.ToMember(target => target.CustomerName)
.FromPath(source => source.Customer.Name);
}
}
var configuration = new ObjectMappingConfiguration();
configuration.AddProfile(new SalesProfile());
Or scan assemblies:
configuration.AddProfilesFromAssemblies(typeof(SalesProfile).Assembly);
16. Constructor mapping
The mapper can create readonly or constructor-based targets by selecting the best public constructor.
public sealed class UserView
{
public UserView(Guid id, string displayName)
{
Id = id;
DisplayName = displayName;
}
public Guid Id { get; }
public string DisplayName { get; }
}
configuration.CreateMap<UserEntity, UserView>()
.ToMember(target => target.DisplayName)
.FromMember(source => source.Name);
var view = entity.MapTo<UserEntity, UserView>(configuration);
Constructor binding respects:
- explicit member rules
FromPath(...)MapFromandMapFromPath- configured converters
When(...)
17. Null path behavior
configuration.ConfigureOptions(options =>
{
options.NullPathBehavior = ObjectMappingNullPathBehavior.Skip;
});
Available behaviors:
Skip: do not assign if an intermediate path segment isnullAssign: assignnullwhen possibleThrow: fail immediately when a path segment isnull
18. Validation
Validate everything:
configuration.Validate();
Validate one explicit map:
configuration.ValidateMap<UserEntity, UserDto>();
Validate the pure convention contract:
configuration.ValidateConventionMap<UserEntity, UserDto>();
ValidateConventionMap and GetConventionValidationError ignore fluent configuration and manual hooks for the same type pair. They are intentionally convention-and-attribute only.
19. Structured validation errors
var errors = configuration.GetValidationErrors();
foreach (var error in errors)
{
Console.WriteLine($"{error.Kind}: {error.Message}");
Console.WriteLine($"Path: {error.SourcePath}");
}
Single explicit map:
var errors = configuration.GetValidationErrors<UserEntity, UserDto>();
Single convention contract:
var error = configuration.GetConventionValidationError<UserEntity, UserDto>();
20. Runtime descriptors and diagnostics
Registered explicit maps:
var registrations = configuration.GetRegisteredMaps();
Explicit map descriptor:
var descriptor = configuration.GetMapDescriptor<UserEntity, UserDto>();
Console.WriteLine(descriptor.Kind); // ExplicitConfiguration
Console.WriteLine(descriptor.UsesExplicitConfiguration); // true
Console.WriteLine(descriptor.HasManualFactory);
Console.WriteLine(descriptor.HasProfileScopedConverters);
Convention contract descriptor:
var descriptor = configuration.GetConventionMapDescriptor<UserEntity, UserDto>();
Effective runtime descriptor:
var descriptor = configuration.GetEffectiveMapDescriptor<UserEntity, UserDto>();
Descriptor semantics:
GetMapDescriptordescribes the explicit registered mapGetConventionMapDescriptordescribes the pure convention-and-attribute contractGetEffectiveMapDescriptordescribes the effective runtime shape used by the mapper
Important notes:
Get*Descriptormethods throw when the requested contract is invalidTryGet*Descriptormethods returnfalsefor known invalid or unavailable contractsGetEffectiveMapDescriptor(..., ConfiguredMembersOnly)still reflects actual runtime fallback members; the validation mode narrows validation, not the effective runtime shape- explicit descriptors are no longer tightened by unrelated convention fallback failures
Inspect members:
foreach (var member in descriptor.Members)
{
Console.WriteLine($"{member.TargetMember} -> {member.SourceKind}");
}
ObjectMemberMapSourceKind can distinguish:
ExplicitMemberExplicitPathExplicitIgnoreAttributeMapFromAttributeMapFromPathAttributeIgnoreGlobalIgnoreConventionUnresolved
21. Precompilation and startup warmup
Compile all explicit maps:
configuration.Validate();
configuration.CompileMaps();
Compile one map:
configuration.CompileMap<UserEntity, UserDto>();
Compile one convention contract:
configuration.CompileConventionMap<UserEntity, UserDto>();
Compile selectively:
configuration.CompileMaps(descriptor =>
descriptor.SourceType.Namespace == "MyApp.Sales");
configuration.CompileMapsForProfile<SalesProfile>();
configuration.CompileMapsFromAssembly(typeof(SalesProfile).Assembly);
22. IObjectMapper
The service facade wraps the core extensions with a stable injectable interface.
public sealed class UserService
{
private readonly IObjectMapper _mapper;
public UserService(IObjectMapper mapper)
{
_mapper = mapper;
}
public UserDto GetDto(UserEntity entity)
{
return _mapper.MapTo<UserEntity, UserDto>(entity);
}
}
It includes:
MapToMapInto- collection mapping
- safe
TryMap* BuildProjectionExpressionProjectTo
It does not expose the mutable configuration object.
23. Queryable projection
Projection is designed for IQueryable providers such as EF Core.
var query = dbContext.Users.ProjectTo<UserEntity, UserDto>(configuration);
Or build the expression directly:
var expression = QueryableProjectionExtensions
.BuildProjectionExpression<UserEntity, UserDto>(configuration);
Projection supports:
- convention member matching
MapFromMapFromPath- fluent
FromMember(...) - fluent
FromPath(...) - built-in type conversions
Projection does not support:
- custom converters
FromSource(...)When(...)MapUsing(...)MapIntoUsing(...)- manual factory hooks
When non-projectable rules are present, BuildProjectionExpression and ProjectTo throw instead of silently degrading.
24. Value type mapping
Map to structs and record structs using MapToValue:
public readonly record struct UserSummary(int Id, string Name);
var summary = entity.MapToValue<UserEntity, UserSummary>();
Constructor matching is the primary mechanism for value-type destinations. Properties not covered by the constructor are set via reflection.
25. Built-in type conversions
The following conversions are handled automatically without registering explicit converters:
| Source | Target | Mechanism |
|---|---|---|
T |
T (same type) |
direct copy |
| derived class | base class | assignable reference |
Nullable<T> |
T |
unwrap with default |
T |
Nullable<T> |
direct wrap |
Nullable<T> |
Nullable<U> |
unwrap, convert, rewrap |
Enum |
Enum (different type) |
by value (default) or by name |
string |
Enum |
Enum.Parse, case-insensitive |
Enum |
string |
ToString() |
string |
int, long, short, byte, double, float, decimal, bool |
Parse with InvariantCulture |
int, long, short, byte, double, float, decimal, bool |
string |
ToString() |
DateTime |
DateOnly |
DateOnly.FromDateTime |
DateTime |
TimeOnly |
TimeOnly.FromDateTime |
DateOnly |
DateTime |
ToDateTime(TimeOnly.MinValue) |
TimeOnly |
TimeSpan |
ToTimeSpan() |
TimeSpan |
TimeOnly |
TimeOnly.FromTimeSpan |
ValueTuple |
ValueTuple (same arity and compatible elements) |
direct copy |
types with op_Implicit / op_Explicit |
target type | conversion operator |
26. Supported collection types
The mapper handles element-type conversion and collection-shape conversion for:
| Collection type | As source | As target |
|---|---|---|
List<T> |
yes | yes |
T[] |
yes | yes |
HashSet<T> |
yes | yes |
LinkedList<T> |
yes | yes |
Dictionary<K, V> |
yes | yes |
IEnumerable<T> |
yes | - |
ICollection<T> |
yes | - |
IList<T> |
yes | - |
ISet<T> |
yes | yes |
IReadOnlyList<T> |
yes | yes |
IReadOnlyCollection<T> |
yes | yes |
IReadOnlySet<T> |
yes | yes |
ImmutableList<T> |
yes | yes |
ImmutableArray<T> |
yes | yes |
ImmutableHashSet<T> |
yes | yes |
Same-element-type conversions (e.g., List<T> to HashSet<T>) are also supported without requiring a converter.
Options
ObjectMappingOptions includes:
IgnoreNullValuesNullPathBehaviorCaseInsensitiveMatchingSourcePrefixToIgnoreTargetPrefixToIgnoreEnumMappingStrategy- auditable member exclusion strategies
- global ignored destination members
Example:
var configuration = new ObjectMappingConfiguration()
.ConfigureOptions(options =>
{
options.IgnoreNullValues = true;
options.CaseInsensitiveMatching = true;
options.SourcePrefixToIgnore = "Src";
options.TargetPrefixToIgnore = "Customer";
options.EnumMappingStrategy = ObjectMappingEnumStrategy.ByName;
});
Performance model
The library is optimized for repeated backend mapping:
- convention maps are cached per source/target pair
- configured maps are cached per source/target/configuration/version
- constructor plans are cached
- configured caches are invalidated when configuration changes
- configured caches use weakly associated storage, so short-lived configurations are not pinned forever
Recommended startup strategy for APIs:
configuration.Validate();
configuration.CompileMaps();
Notes and warnings
MapReadOnlyListToreturns a true read-only listTryGet*Descriptoris the non-throwing probe API- effective descriptors for manual maps are intentionally opaque
ProjectTosupports only expression-safe rulesTryMapIntois best-effort safe for top-level writable members, not deep graph transactions
Companion packages
This repository contains only the core runtime mapper.
Companion repositories:
Pitasoft.ObjectMapping.DependencyInjectionExtensionsPitasoft.ObjectMapping.Generator
Castellano
Pitasoft.ObjectMapping es una librería .NET de alto rendimiento para mapeo de objetos en backend.
Está pensada para escenarios como:
Entity -> DTODTO -> Entity- actualizaciones parciales sobre entidades ya cargadas
- flattening de estructuras anidadas
- mapeo repetido de alto volumen en APIs y servicios
- validación, diagnóstico y precompilación en startup
Instalación
dotnet add package Pitasoft.ObjectMapping
Paquetes complementarios:
dotnet add package Pitasoft.ObjectMapping.DependencyInjectionExtensions
dotnet add package Pitasoft.ObjectMapping.Generator
Qué incluye
- mapeo por convención
- atributos
MapFrom,MapFromPath,MapIgnore - configuración fluida con perfiles
MapIntopara actualizar instancias existentes- mapeo de miembros seleccionados
- mapeo de colecciones
- API seguras
TryMap* - soporte de constructor mapping
- validación y errores estructurados
- descriptores de runtime para tooling
- precompilación
- proyección
IQueryablepara reglas proyectables
Guía rápida de decisión
| Escenario | Opción recomendada |
|---|---|
| nombres iguales entre origen y destino | convención |
| uno o dos renombrados | atributos |
| contrato importante de aplicación | configuración fluida |
| muchos mapas relacionados | perfiles |
patch DTO con null que no debe sobrescribir |
MapInto + IgnoreNullValues |
| quieres eliminar coste de primer uso | Validate() + CompileMaps*() |
| necesitas lógica de negocio | MapUsing, MapIntoUsing, callbacks |
| necesitas inspección o tooling | descriptores |
| necesitas EF Core projection | ProjectTo, con límites explícitos |
Ejemplos principales
1. Mapeo por convención
var dto = entity.MapTo<UserEntity, UserDto>();
2. Actualizar un destino existente
entity.MapInto(existingDto);
3. Seleccionar solo algunos miembros
var dto = entity.MapMembersTo<UserEntity, UserDto>("Id", "Name");
entity.MapMembersInto(existingDto,
target => target.Name,
target => target.Email);
4. Atributos
public sealed class OrderDto
{
[MapFrom(nameof(OrderEntity.Number))]
public string OrderNumber { get; set; } = string.Empty;
[MapFromPath("Customer.Name")]
public string CustomerName { get; set; } = string.Empty;
[MapIgnore]
public string InternalNotes { get; set; } = string.Empty;
}
5. Configuración fluida
configuration.CreateMap<OrderEntity, OrderDto>()
.ToMember(target => target.CustomerCity)
.FromPath(source => source.Customer.Address.City);
configuration.CreateMap<UserPatchDto, UserEntity>()
.ToMember(target => target.Email)
.When(source => !string.IsNullOrWhiteSpace(source.Email))
.FromMember(source => source.Email!);
configuration.CreateMap<UserEntity, UserSummaryDto>()
.ToMember(target => target.DisplayLabel)
.FromSource(source => $"{source.Name} <{source.Email}>");
6. Converters
configuration.AddConverter<string, Guid>(value => Guid.Parse(value));
7. Callbacks y mapping manual
configuration.CreateMap<CreateUserDto, UserEntity>()
.BeforeMap((source, target) => target.CreatedAtUtc = DateTime.UtcNow)
.AfterMap((source, target) => target.NormalizedEmail = target.Email.ToUpperInvariant());
configuration.CreateMap<LegacyUserRow, UserEntity>()
.MapUsing(source => new UserEntity
{
Id = source.UserId,
Name = source.FullName,
Email = source.Mail
});
8. Colecciones
var list = users.MapListTo<UserEntity, UserDto>();
var readOnly = users.MapReadOnlyListTo<UserEntity, UserDto>();
var array = users.MapArrayTo<UserEntity, UserDto>();
9. APIs seguras
if (entity.TryMapTo<UserEntity, UserDto>(out var dto))
{
// dto disponible
}
if (!entity.TryMapInto(existingDto))
{
// fallo de mapeo
}
TryMapInto hace rollback best-effort de propiedades top-level escribibles. No es una transacción profunda sobre todo el grafo.
10. Validation
configuration.Validate();
configuration.ValidateMap<UserEntity, UserDto>();
configuration.ValidateConventionMap<UserEntity, UserDto>();
Errores estructurados:
var errors = configuration.GetValidationErrors();
var explicitErrors = configuration.GetValidationErrors<UserEntity, UserDto>();
var conventionError = configuration.GetConventionValidationError<UserEntity, UserDto>();
ValidateConventionMap y GetConventionValidationError validan solo el contrato de convención y atributos. No usan reglas fluidas ni hooks manuales del mismo par de tipos.
11. Descriptores
var explicitDescriptor = configuration.GetMapDescriptor<UserEntity, UserDto>();
var conventionDescriptor = configuration.GetConventionMapDescriptor<UserEntity, UserDto>();
var effectiveDescriptor = configuration.GetEffectiveMapDescriptor<UserEntity, UserDto>();
Semántica:
GetMapDescriptordescribe el mapa explícito registradoGetConventionMapDescriptordescribe el contrato puro de convención y atributosGetEffectiveMapDescriptordescribe el shape efectivo que usa el runtime
Notas importantes:
Get*Descriptorlanza excepción si el contrato pedido es inválidoTryGet*Descriptordevuelvefalseen esos casos conocidosGetEffectiveMapDescriptor(..., ConfiguredMembersOnly)sigue reflejando el fallback real del runtime- los mapas manuales tienen descriptor efectivo opaco
12. Precompilación
configuration.Validate();
configuration.CompileMaps();
configuration.CompileMapsForProfile<SalesProfile>();
configuration.CompileMapsFromAssembly(typeof(SalesProfile).Assembly);
configuration.CompileMap<UserEntity, UserDto>();
configuration.CompileConventionMap<UserEntity, UserDto>();
13. IObjectMapper
public sealed class UserService
{
private readonly IObjectMapper _mapper;
public UserService(IObjectMapper mapper)
{
_mapper = mapper;
}
public UserDto GetDto(UserEntity entity)
{
return _mapper.MapTo<UserEntity, UserDto>(entity);
}
}
La fachada de servicio incluye mapping, TryMap* y proyección, pero no expone la configuración mutable.
14. Proyección IQueryable
var query = dbContext.Users.ProjectTo<UserEntity, UserDto>(configuration);
Soporta:
- convención
MapFromMapFromPathFromMember(...)FromPath(...)- conversiones built-in
No soporta:
- converters personalizados
FromSource(...)When(...)MapUsing(...)MapIntoUsing(...)- hooks manuales
Cuando una regla no es proyectable, ProjectTo y BuildProjectionExpression lanzan excepción de forma explícita.
15. Mapeo a value types
Usa MapToValue para mapear a structs y record structs:
public readonly record struct UserSummary(int Id, string Name);
var summary = entity.MapToValue<UserEntity, UserSummary>();
El mecanismo principal es constructor matching. Las propiedades no cubiertas por el constructor se asignan por reflexión.
16. Conversiones automáticas
Las siguientes conversiones se aplican sin registrar converters:
| Origen | Destino | Mecanismo |
|---|---|---|
T |
T (mismo tipo) |
copia directa |
Nullable<T> |
T |
unwrap con default |
T |
Nullable<T> |
wrap directo |
Enum |
Enum (otro tipo) |
por valor (default) o por nombre |
string |
Enum |
Enum.Parse, case-insensitive |
Enum |
string |
ToString() |
string |
int, long, short, byte, double, float, decimal, bool |
Parse con InvariantCulture |
int, long, short, byte, double, float, decimal, bool |
string |
ToString() |
DateTime |
DateOnly |
DateOnly.FromDateTime |
DateTime |
TimeOnly |
TimeOnly.FromDateTime |
DateOnly |
DateTime |
ToDateTime(TimeOnly.MinValue) |
TimeOnly |
TimeSpan |
ToTimeSpan() |
TimeSpan |
TimeOnly |
TimeOnly.FromTimeSpan |
ValueTuple |
ValueTuple (misma aridad y elementos compatibles) |
copia directa |
tipos con op_Implicit / op_Explicit |
tipo destino | operador de conversión |
17. Colecciones soportadas
El mapper soporta conversión de elemento y de forma de colección:
| Tipo | Como origen | Como destino |
|---|---|---|
List<T> |
sí | sí |
T[] |
sí | sí |
HashSet<T> |
sí | sí |
LinkedList<T> |
sí | sí |
Dictionary<K, V> |
sí | sí |
IEnumerable<T> |
sí | - |
ICollection<T> |
sí | - |
IList<T> |
sí | - |
ISet<T> |
sí | sí |
IReadOnlyList<T> |
sí | sí |
IReadOnlyCollection<T> |
sí | sí |
IReadOnlySet<T> |
sí | sí |
ImmutableList<T> |
sí | sí |
ImmutableArray<T> |
sí | sí |
ImmutableHashSet<T> |
sí | sí |
También se soportan conversiones de mismo tipo de elemento (e.g., List<T> a HashSet<T>) sin necesidad de converter.
Opciones
ObjectMappingOptions soporta:
IgnoreNullValuesNullPathBehaviorCaseInsensitiveMatchingSourcePrefixToIgnoreTargetPrefixToIgnoreEnumMappingStrategy- estrategias para miembros auditables
- miembros destino ignorados globalmente
Rendimiento
El paquete está optimizado para uso repetido:
- mapas por convención cacheados por par de tipos
- mapas configurados cacheados por par de tipos, instancia de configuración y versión
- planes de constructor cacheados
- invalidación segura cuando cambia la configuración
- almacenamiento configurado con asociación débil para no anclar configuraciones efímeras
Resumen práctico
- usa convención para lo simple
- usa atributos para pequeños renombrados
- usa configuración fluida para contratos importantes
- usa descriptores para tooling y diagnóstico
- usa
CompileMaps*()si quieres evitar el coste del primer uso - usa
ProjectTosolo con reglas expresables comoExpression
Autor
Sebastián Martínez Pérez
Licencia
Copyright © 2020-2026 Pitasoft, S.L.
Licenciado bajo los términos de la LICENSE.txt incluida en este repositorio.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. 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 is compatible. 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 is compatible. 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. |
-
net10.0
- No dependencies.
-
net8.0
- No dependencies.
-
net9.0
- No dependencies.
NuGet packages (1)
Showing the top 1 NuGet packages that depend on Pitasoft.ObjectMapping:
| Package | Downloads |
|---|---|
|
Pitasoft.ObjectMapping.DependencyInjectionExtensions
Dependency injection extensions for Pitasoft.ObjectMapping. Adds IServiceCollection registration, profile scanning and startup validation. |
GitHub repositories
This package is not used by any popular GitHub repositories.