Pitasoft.ObjectMapping
1.0.2
See the version list below for details.
dotnet add package Pitasoft.ObjectMapping --version 1.0.2
NuGet\Install-Package Pitasoft.ObjectMapping -Version 1.0.2
<PackageReference Include="Pitasoft.ObjectMapping" Version="1.0.2" />
<PackageVersion Include="Pitasoft.ObjectMapping" Version="1.0.2" />
<PackageReference Include="Pitasoft.ObjectMapping" />
paket add Pitasoft.ObjectMapping --version 1.0.2
#r "nuget: Pitasoft.ObjectMapping, 1.0.2"
#:package Pitasoft.ObjectMapping@1.0.2
#addin nuget:?package=Pitasoft.ObjectMapping&version=1.0.2
#tool nuget:?package=Pitasoft.ObjectMapping&version=1.0.2
Pitasoft.ObjectMapping
English
Pitasoft.ObjectMapping is a .NET library for backend object mapping.
It is designed for scenarios such as:
Entity -> DTODTO -> Entity- partial updates over existing entities
- flattening nested source members into flat DTOs
- high-volume repeated mapping in backend services
Installation
dotnet add package Pitasoft.ObjectMapping
Companion packages:
dotnet add package Pitasoft.ObjectMapping.DependencyInjectionExtensions
dotnet add package Pitasoft.ObjectMapping.Generator
What This Package Includes
- convention-based mapping
- mapping into existing targets
- partial member selection
- collection mapping
- mapping attributes:
MapFrom,MapFromPath,MapIgnore - fluent configuration with profiles, converters, callbacks, validation, and manual mapping hooks
- null-handling and auditable-member options
- cached delegates for repeated mappings
Core API
| Area | API |
|---|---|
| Create a new destination | MapTo<TSource, TTarget>() |
| Update an existing destination | MapInto<TSource, TTarget>() |
| Map selected members | MapMembersTo, MapMembersInto, expression-based overloads |
| Collections | MapListTo, MapReadOnlyListTo, MapArrayTo |
| Attributes | MapFrom, MapFromPath, MapIgnore |
| Fluent configuration | ObjectMappingConfiguration, CreateMap, ToMember, FromMember, FromPath, Ignore |
| Profiles | IObjectMappingProfile, ObjectMappingProfile, AddProfile, AddProfilesFromAssemblies |
| Validation and diagnostics | Validate, ValidateMap, ValidateConventionMap, GetValidationErrors, GetValidationErrors<TSource, TTarget>, GetConventionValidationError, GetRegisteredMaps, GetMapDescriptors, GetMapDescriptor, TryGetMapDescriptor, GetConventionMapDescriptor, TryGetConventionMapDescriptor, GetEffectiveMapDescriptor, TryGetEffectiveMapDescriptor, CompileMaps, CompileMaps(Predicate<...>), CompileMapsForProfile, CompileMapsFromAssembly, CompileMap, CompileConventionMap, ObjectMappingValidationMode |
| Customization | BeforeMap, AfterMap, MapUsing, MapIntoUsing |
| Options | IgnoreNullValues, NullPathBehavior, IgnoreDestinationMembers, UseAuditableMemberStrategy |
| Service facade | IObjectMapper, ObjectMapper |
| Safe mapping | TryMapTo, TryMapInto, TryMapListTo, TryMapReadOnlyListTo, TryMapArrayTo |
Which option should I use?
| Scenario | Recommended option |
|---|---|
| source and destination share the same member names | convention-based MapTo or MapInto |
| a DTO has only one or two renamed members | attributes with MapFrom or MapFromPath |
| the map is part of an application contract | fluent configuration with CreateMap |
| the map belongs to a bounded context or feature module | profile-based configuration |
update DTOs should keep existing values when members are null |
MapInto with IgnoreNullValues = true |
| nested flattening must be validated and precompiled | FromPath(...) in fluent configuration |
| the mapping is highly custom or business-specific | MapUsing or MapIntoUsing |
| startup latency matters more than lazy first-hit cost | Validate() plus CompileMaps*() |
Resolution Rules
Mapping resolves destination members in this order:
- fluent configuration
MapFromAttributeMapFromPathAttribute- direct member name match
General rules:
- destination members must be writable
- source members must be readable
- mapping is shallow unless
FromPath(...)orMapFromPathAttributeis used - member types must match unless a converter is configured
- delegates are compiled and cached for reuse
Usage
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;
options.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 in this example:
MapTocreates a newCustomerDtoFromPath(...)flattensAddress.CityintoCustomerDto.CityMapIntoupdates the tracked entity instanceIgnoreNullValues = truekeeps the existingEmail- the auditable strategy avoids copying common audit members during updates
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 entity = new UserEntity
{
Id = 10,
Name = "Ada Lovelace",
Email = "ada@example.com"
};
var dto = entity.MapTo<UserEntity, UserDto>();
Mapping into an existing destination
var dto = new UserDto();
entity.MapInto(dto);
Mapping only selected members
var dto = entity.MapMembersTo<UserEntity, UserDto>("Id", "Name");
var existing = new UserDto { Id = 99, Name = "Old", Email = "old@example.com" };
entity.MapMembersInto(existing, "Name");
Expression-based overloads are available when you want compile-time member selection:
var dto = entity.MapMembersTo<UserEntity, UserDto>(
target => target.Id,
target => target.Name);
entity.MapMembersInto(existing,
target => target.Name,
target => target.Email);
Collection mapping
var list = users.MapListTo<UserEntity, UserDto>();
var readOnlyList = users.MapReadOnlyListTo<UserEntity, UserDto>();
var array = users.MapArrayTo<UserEntity, UserDto>();
If you already have a mapped configuration, the same collection API works with it:
var configuration = new ObjectMappingConfiguration();
configuration.CreateMap<UserEntity, UserDto>()
.ToMember(target => target.DisplayName)
.FromMember(source => source.Name);
var dtoList = users.MapListTo<UserEntity, UserDto>(configuration);
Safe mapping with TryMapTo
if (entity.TryMapTo<UserEntity, UserDto>(out var dto))
{
// dto is available
}
You can also protect mapping into an existing target:
var target = new UserDto();
if (entity.TryMapInto(target))
{
// target was updated
}
Safe collection mapping is also available:
if (users.TryMapListTo<UserEntity, UserDto>(out var list))
{
// list available
}
if (users.TryMapReadOnlyListTo<UserEntity, UserDto>(out var readOnlyList))
{
// readOnlyList available
}
if (users.TryMapArrayTo<UserEntity, UserDto>(out var array))
{
// array available
}
Use TryMap* when mapping is optional and you do not want to throw or branch around null/invalid inputs at the call site.
Attributes
MapFrom
using Pitasoft.ObjectMapping.Attributes;
public sealed class CustomerEntity
{
public Guid Id { get; set; }
public string Name { get; set; } = string.Empty;
}
public sealed class CustomerDto
{
[MapFrom("Id")]
public Guid CustomerId { get; set; }
[MapFrom("Name")]
public string FullName { get; set; } = string.Empty;
}
var dto = entity.MapTo<CustomerEntity, CustomerDto>();
MapFromPath
using Pitasoft.ObjectMapping.Attributes;
public sealed class OrderDto
{
public int Id { get; set; }
[MapFromPath("Customer.Name")]
public string CustomerName { get; set; } = string.Empty;
[MapFromPath("Customer.Address.City")]
public string? City { get; set; }
}
var dto = order.MapTo<OrderEntity, OrderDto>();
MapIgnore
using Pitasoft.ObjectMapping.Attributes;
public sealed class UserDto
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
[MapIgnore]
public string InternalNotes { get; set; } = string.Empty;
}
var dto = entity.MapTo<UserEntity, UserDto>();
Fluent Configuration
Different member names
using Pitasoft.ObjectMapping.Configuration;
var configuration = new ObjectMappingConfiguration();
configuration.CreateMap<CustomerEntity, CustomerDto>()
.ToMember(dto => dto.CustomerId).FromMember(entity => entity.Id)
.ToMember(dto => dto.FullName).FromMember(entity => entity.Name);
var dto = entity.MapTo<CustomerEntity, CustomerDto>(configuration);
Flatten nested members
configuration.CreateMap<OrderEntity, OrderDto>()
.ToMember(dto => dto.Id).FromMember(entity => entity.Id)
.ToMember(dto => dto.CustomerName).FromPath(entity => entity.Customer!.Name)
.ToMember(dto => dto.City).FromPath(entity => entity.Customer!.Address!.City);
This is the recommended approach when nested flattening is part of an application contract and you want validation support.
Update DTO → Entity with ignored nulls
var configuration = new ObjectMappingConfiguration()
.ConfigureOptions(options =>
{
options.IgnoreNullValues = true;
options.UseAuditableMemberStrategy(ObjectMappingAuditableMemberStrategy.IgnoreCommonMembers);
});
updateDto.MapInto(entity, configuration);
This is one of the most common backend patterns:
- load entity from your repository
- apply an update DTO over the tracked entity
- keep existing values when DTO members are
null
Global converter
var configuration = new ObjectMappingConfiguration()
.AddConverter<string, int>(value => int.Parse(value));
var dto = source.MapTo<ExternalSource, InternalDto>(configuration);
Member-specific converter
configuration.CreateMap<ExternalCustomer, ExternalCustomerDto>()
.ToMember(target => target.Id)
.FromMember(source => source.Identifier, value => int.Parse(value));
Use a member-specific converter when the conversion rule is local to one DTO instead of something you want available globally.
Profiles
public sealed class CustomerProfile : ObjectMappingProfile
{
public override void Configure(ObjectMappingConfiguration configuration)
{
configuration.CreateMap<CustomerEntity, CustomerDto>()
.ToMember(target => target.Id).FromMember(source => source.Id)
.ToMember(target => target.Name).FromMember(source => source.Name);
}
}
var configuration = new ObjectMappingConfiguration()
.AddProfile(new CustomerProfile());
Profiles are useful when:
- you want one mapping module per feature or bounded context
- startup should scan or precompile maps by profile
- the same application has many unrelated mapping groups
Profile-scoped converter
public sealed class BillingProfile : ObjectMappingProfile
{
public override void Configure(ObjectMappingConfiguration configuration)
{
configuration.AddConverter<decimal, string>(value => value.ToString("0.00"));
configuration.CreateMap<InvoiceEntity, InvoiceDto>()
.ToMember(target => target.Total).FromMember(source => source.Total);
}
}
Converter precedence is:
- member-specific converter
- profile-scoped converter
- global converter
Manual customization
configuration.CreateMap<UserEntity, UserDto>()
.AfterMap((source, target) => target.FullName = $"{source.Name} {source.Surname}");
You can combine callbacks:
configuration.CreateMap<UserEntity, UserDto>()
.BeforeMap((source, target) => target.FullName = string.Empty)
.AfterMap((source, target) => target.FullName = $"{source.Name} {source.Surname}")
.AfterMap((source, target) => target.Email = target.Email.Trim().ToLowerInvariant());
Manual factory
configuration.CreateMap<UserEntity, UserDto>()
.MapUsing(source => new UserDto
{
Id = source.Id,
FullName = $"{source.Name} {source.Surname}"
});
Use MapUsing(...) when the map is effectively custom code and convention would only add noise.
Manual update
configuration.CreateMap<UpdateUserDto, UserEntity>()
.MapIntoUsing((source, target) =>
{
if (source.Name is not null)
{
target.Name = source.Name;
}
});
Use MapIntoUsing(...) when update semantics are business-specific and should remain explicit.
Null path behavior
By default, FromPath(...) and MapFromPathAttribute use NullPathBehavior.Skip.
var configuration = new ObjectMappingConfiguration()
.ConfigureOptions(options =>
{
options.NullPathBehavior = ObjectMappingNullPathBehavior.Skip;
});
Available behaviors:
Skip: keep the current destination valueAssign: assignnullwhen the destination allows itThrow: fail fast when a nested segment isnull
Example with Throw:
var configuration = new ObjectMappingConfiguration()
.ConfigureOptions(options =>
{
options.NullPathBehavior = ObjectMappingNullPathBehavior.Throw;
});
configuration.CreateMap<OrderEntity, OrderDto>()
.ToMember(target => target.City).FromPath(source => source.Customer!.Address!.City);
Validation
configuration.Validate();
configuration.Validate(ObjectMappingValidationMode.AllWritableDestinationMembers);
configuration.ValidateMap<CustomerEntity, CustomerDto>();
configuration.ValidateConventionMap<CustomerEntity, CustomerDto>();
If you want structured validation data without exceptions:
var errors = configuration.GetValidationErrors();
var customerErrors = configuration.GetValidationErrors<CustomerEntity, CustomerDto>();
var conventionError = configuration.GetConventionValidationError<CustomerEntity, CustomerDto>();
var registeredMaps = configuration.GetRegisteredMaps();
GetValidationErrors<TSource, TTarget>() inspects only explicitly registered maps.
If you need convention or attribute-based validation for a type pair without explicit configuration, use GetConventionValidationError<TSource, TTarget>().
Use validation in these cases:
- startup checks before serving requests
- CI tests for mapping contracts
- precompilation workflows
- feature modules that register profiles dynamically
When a nested path is invalid, structured validation errors include the original source path:
var errors = configuration.GetValidationErrors<OrderEntity, OrderDto>();
if (errors.Count > 0)
{
var error = errors[0];
Console.WriteLine(error.Kind);
Console.WriteLine(error.SourcePath);
}
Typical structured error handling:
var errors = configuration.GetValidationErrors();
foreach (var error in errors)
{
Console.WriteLine($"{error.Kind} | {error.SourceType.Name} -> {error.TargetType.Name}");
Console.WriteLine(error.Message);
}
Map descriptors for tooling and diagnostics
The runtime configuration can expose explicit map metadata without depending on internal caches or delegates:
var descriptors = configuration.GetMapDescriptors();
var customerMap = configuration.GetMapDescriptor<CustomerEntity, CustomerDto>();
if (configuration.TryGetMapDescriptor<CustomerEntity, CustomerDto>(out var descriptor))
{
var targetMembers = descriptor.Members.Select(member => member.TargetMember).ToArray();
}
You can also inspect how each member is resolved:
foreach (var member in customerMap.Members)
{
Console.WriteLine($"{member.TargetMember} <- {member.SourcePath ?? member.SourceMember} ({member.SourceKind})");
}
Descriptors are useful for:
- diagnostics and startup reporting
- custom tooling
- documentation generation
- keeping runtime configuration visible to companion packages
Runtime descriptor scope:
- descriptors represent explicit runtime configuration
- they do not expand convention-only members
- they do not expose compiled delegates or internal cache structures
- they provide a stable surface for diagnostics and companion tooling
If you need to inspect the effective convention and attribute-based contract for a pair of types, use:
var conventionDescriptor = configuration.GetConventionMapDescriptor<CustomerEntity, CustomerDto>();
if (configuration.TryGetConventionMapDescriptor<CustomerEntity, CustomerDto>(out var descriptor))
{
var members = descriptor.Members.Select(member => member.TargetMember).ToArray();
}
If you need the descriptor that the runtime engine will effectively use, ask for the effective runtime map:
var effectiveDescriptor = configuration.GetEffectiveMapDescriptor<CustomerEntity, CustomerDto>();
This is especially useful when you want to know whether runtime will use:
- an explicit fluent map
- attributes
- or pure convention
Descriptor selection guide:
| API | Use it when | Notes |
|---|---|---|
GetMapDescriptor |
you want registered fluent/profile configuration only | UsesExplicitConfiguration is true |
GetConventionMapDescriptor |
you want the convention and attribute contract for a type pair | ignores explicit fluent rules |
GetEffectiveMapDescriptor |
you want to know what the runtime engine will actually use | explicit map wins, otherwise convention contract |
Descriptor kinds:
ExplicitConfigurationConventionContractEffectiveRuntimeMap
Member source kinds:
ExplicitMemberExplicitPathExplicitIgnoreAttributeMapFromAttributeMapFromPathAttributeIgnoreGlobalIgnoreConventionUnresolved
Tooling performance note:
- descriptor APIs are intended for startup diagnostics, reporting, and companion tooling
- they are cached per configuration version, so repeated reads stay inexpensive
- validation APIs are still more expensive than descriptor reads and should stay out of hot mapping paths
Precompilation
Configured and convention-based maps are compiled lazily on first use. If you want to remove first-hit latency in backend applications, you can precompile them during startup:
configuration.CompileMaps();
configuration.CompileMaps(descriptor => descriptor.ProfileType == typeof(CustomerProfile));
configuration.CompileMapsForProfile<CustomerProfile>();
configuration.CompileMapsFromAssembly(typeof(CustomerProfile).Assembly);
configuration.CompileMap<CustomerEntity, CustomerDto>();
configuration.CompileConventionMap<CustomerEntity, CustomerDto>();
Typical startup flow:
configuration.Validate();
configuration.CompileMapsForProfile<CustomerProfile>();
Use precompilation when:
- the application has a stable set of known maps
- predictable first-request latency matters
- you want startup to absorb delegate compilation cost
Validation modes:
ConfiguredMembersOnlyAllWritableDestinationMembers
Pitasoft.DataAccess Integration
Recommended pattern:
Pitasoft.DataAccessmaterializes entitiesPitasoft.ObjectMappingtransforms them in memoryPitasoft.Resultrepresents success and failurePitasoft.Result.AspNetCoretranslates results to HTTP responses
Typical read flow:
var customer = await repository.GetByIdAsync(id, cancellationToken);
var dto = customer.MapTo<CustomerEntity, CustomerDto>(configuration);
Typical update flow:
var customer = await repository.GetByIdAsync(id, cancellationToken);
updateDto.MapInto(customer, configuration);
await repository.SaveChangesAsync(cancellationToken);
Recommended service pattern:
public sealed class CustomerApplicationService
{
private readonly ICustomerRepository _repository;
private readonly ObjectMappingConfiguration _mapping;
public CustomerApplicationService(
ICustomerRepository repository,
ObjectMappingConfiguration mapping)
{
_repository = repository;
_mapping = mapping;
}
public async Task<CustomerDto?> GetAsync(Guid id, CancellationToken cancellationToken)
{
var entity = await _repository.GetByIdAsync(id, cancellationToken);
return entity?.MapTo<CustomerEntity, CustomerDto>(_mapping);
}
public async Task UpdateAsync(Guid id, UpdateCustomerDto request, CancellationToken cancellationToken)
{
var entity = await _repository.GetByIdAsync(id, cancellationToken)
?? throw new InvalidOperationException("Customer not found.");
request.MapInto(entity, _mapping);
await _repository.SaveChangesAsync(cancellationToken);
}
}
Notes
MapTocreates a new destination instanceMapIntoupdates an existing destination instanceNullPathBehaviordefaults toSkip- for backend updates,
IgnoreNullValues = trueis usually the safest option - use fluent configuration instead of attributes when a map is part of an application contract
Castellano
Pitasoft.ObjectMapping es una librería .NET para mapeo de objetos en backend.
Está pensada para escenarios como:
Entity -> DTODTO -> Entity- actualizaciones parciales sobre entidades existentes
- flattening de miembros anidados hacia DTOs planos
- mapeo repetido de alto volumen en servicios backend
Instalación
dotnet add package Pitasoft.ObjectMapping
Paquetes complementarios:
dotnet add package Pitasoft.ObjectMapping.DependencyInjectionExtensions
dotnet add package Pitasoft.ObjectMapping.Generator
Qué incluye este paquete
- mapeo por convención
- mapeo sobre destinos existentes
- selección parcial de miembros
- mapeo de colecciones
- atributos de mapeo:
MapFrom,MapFromPath,MapIgnore - configuración fluida con perfiles, converters, callbacks, validación y hooks manuales
- control de nulos y exclusión de miembros auditables
- caché de delegates para mapeos repetidos
API principal
| Área | API |
|---|---|
| Crear un destino nuevo | MapTo<TSource, TTarget>() |
| Actualizar un destino existente | MapInto<TSource, TTarget>() |
| Mapear miembros seleccionados | MapMembersTo, MapMembersInto, sobrecargas por expresiones |
| Colecciones | MapListTo, MapReadOnlyListTo, MapArrayTo |
| Atributos | MapFrom, MapFromPath, MapIgnore |
| Configuración fluida | ObjectMappingConfiguration, CreateMap, ToMember, FromMember, FromPath, Ignore |
| Perfiles | IObjectMappingProfile, ObjectMappingProfile, AddProfile, AddProfilesFromAssemblies |
| Validación y diagnóstico | Validate, ValidateMap, ValidateConventionMap, GetValidationErrors, GetValidationErrors<TSource, TTarget>, GetConventionValidationError, GetRegisteredMaps, GetMapDescriptors, GetMapDescriptor, TryGetMapDescriptor, GetConventionMapDescriptor, TryGetConventionMapDescriptor, GetEffectiveMapDescriptor, TryGetEffectiveMapDescriptor, CompileMaps, CompileMaps(Predicate<...>), CompileMapsForProfile, CompileMapsFromAssembly, CompileMap, CompileConventionMap, ObjectMappingValidationMode |
| Personalización | BeforeMap, AfterMap, MapUsing, MapIntoUsing |
| Opciones | IgnoreNullValues, NullPathBehavior, IgnoreDestinationMembers, UseAuditableMemberStrategy |
| Fachada de servicio | IObjectMapper, ObjectMapper |
| Mapeo seguro | TryMapTo, TryMapInto, TryMapListTo, TryMapReadOnlyListTo, TryMapArrayTo |
Qué opción usar
| Escenario | Opción recomendada |
|---|---|
| origen y destino comparten los mismos nombres de miembros | MapTo o MapInto por convención |
| un DTO solo renombra uno o dos miembros | atributos con MapFrom o MapFromPath |
| el mapa forma parte del contrato de la aplicación | configuración fluida con CreateMap |
| el mapa pertenece a un módulo o bounded context | perfiles |
un DTO de update debe conservar valores existentes cuando llegan null |
MapInto con IgnoreNullValues = true |
| el flattening anidado debe validarse y precompilarse | FromPath(...) en configuración fluida |
| el mapeo es muy específico o dependiente de reglas de negocio | MapUsing o MapIntoUsing |
| importa más la latencia de arranque controlada que el coste lazy del primer uso | Validate() junto con CompileMaps*() |
Reglas de resolución
El mapeo resuelve miembros destino en este orden:
- configuración fluida
MapFromAttributeMapFromPathAttribute- coincidencia directa por nombre
Reglas generales:
- los miembros destino deben ser escribibles
- los miembros origen deben ser legibles
- el mapeo es superficial salvo que se use
FromPath(...)oMapFromPathAttribute - los tipos deben coincidir salvo que exista un converter configurado
- los delegates se compilan y cachean para reutilización
Ejemplos rápidos
Escenario completo Entity -> DTO -> Update DTO -> Entity:
var configuration = new ObjectMappingConfiguration()
.ConfigureOptions(options =>
{
options.IgnoreNullValues = true;
options.UseAuditableMemberStrategy(ObjectMappingAuditableMemberStrategy.IgnoreCommonMembers);
});
configuration.CreateMap<CustomerEntity, CustomerDto>()
.ToMember(target => target.City).FromPath(source => source.Address.City);
var dto = entity.MapTo<CustomerEntity, CustomerDto>(configuration);
updateDto.MapInto(entity, configuration);
Qué ocurre en este flujo:
MapTocrea un DTO nuevoFromPath(...)aplana miembros anidadosMapIntoactualiza la entidad cargadaIgnoreNullValues = trueconserva los valores existentes- la estrategia auditable evita copiar miembros comunes de auditoría
var dto = entity.MapTo<Entity, EntityDto>();
entity.MapInto(existingDto);
var selected = entity.MapMembersTo<Entity, EntityDto>("Id", "Name");
var list = entities.MapListTo<Entity, EntityDto>();
var readOnlyList = entities.MapReadOnlyListTo<Entity, EntityDto>();
Las mismas APIs de colección funcionan también con configuración fluida:
var configuration = new ObjectMappingConfiguration();
configuration.CreateMap<UserEntity, UserDto>()
.ToMember(target => target.DisplayName)
.FromMember(source => source.Name);
var dtoList = users.MapListTo<UserEntity, UserDto>(configuration);
Selección por expresiones:
var selected = entity.MapMembersTo<Entity, EntityDto>(
target => target.Id,
target => target.Name);
entity.MapMembersInto(existingDto,
target => target.Name,
target => target.Email);
Mapeo seguro:
if (entity.TryMapTo<Entity, EntityDto>(out var dto))
{
// dto disponible
}
También puedes proteger el mapeo sobre un destino existente:
var target = new EntityDto();
if (entity.TryMapInto(target))
{
// target actualizado
}
También puedes proteger colecciones completas:
if (entities.TryMapListTo<Entity, EntityDto>(out var list))
{
// list disponible
}
if (entities.TryMapReadOnlyListTo<Entity, EntityDto>(out var readOnlyList))
{
// readOnlyList disponible
}
if (entities.TryMapArrayTo<Entity, EntityDto>(out var array))
{
// array disponible
}
TryMap* es útil cuando el mapeo es opcional y quieres evitar excepciones o comprobaciones repetidas en el punto de llamada.
Configuración fluida
var configuration = new ObjectMappingConfiguration();
configuration.CreateMap<CustomerEntity, CustomerDto>()
.ToMember(dto => dto.CustomerId).FromMember(entity => entity.Id)
.ToMember(dto => dto.FullName).FromMember(entity => entity.Name);
var dto = entity.MapTo<CustomerEntity, CustomerDto>(configuration);
Flattening con FromPath
configuration.CreateMap<OrderEntity, OrderDto>()
.ToMember(dto => dto.CustomerName).FromPath(entity => entity.Customer!.Name)
.ToMember(dto => dto.City).FromPath(entity => entity.Customer!.Address!.City);
Este es el enfoque recomendado cuando el flattening anidado forma parte del contrato de la aplicación y quieres validarlo.
Update parcial con nulos ignorados
var configuration = new ObjectMappingConfiguration()
.ConfigureOptions(options =>
{
options.IgnoreNullValues = true;
options.UseAuditableMemberStrategy(ObjectMappingAuditableMemberStrategy.IgnoreCommonMembers);
});
updateDto.MapInto(entity, configuration);
Es uno de los patrones más habituales en backend:
- cargar la entidad desde el repositorio
- aplicar un DTO parcial sobre la entidad trackeada
- mantener los valores existentes cuando el DTO trae
null
Converters globales y por miembro
var configuration = new ObjectMappingConfiguration()
.AddConverter<string, int>(value => int.Parse(value));
configuration.CreateMap<ExternalCustomer, ExternalCustomerDto>()
.ToMember(target => target.Id)
.FromMember(source => source.Identifier, value => int.Parse(value));
Usa un converter global cuando la conversión sea transversal a muchos mapas. Usa un converter por miembro cuando la regla sea local a un DTO concreto.
Perfiles y converter por perfil
public sealed class BillingProfile : ObjectMappingProfile
{
public override void Configure(ObjectMappingConfiguration configuration)
{
configuration.AddConverter<decimal, string>(value => value.ToString("0.00"));
configuration.CreateMap<InvoiceEntity, InvoiceDto>()
.ToMember(target => target.Total).FromMember(source => source.Total);
}
}
Precedencia de converters:
- converter por miembro
- converter del perfil
- converter global
Personalización manual
configuration.CreateMap<UserEntity, UserDto>()
.BeforeMap((source, target) => target.FullName = string.Empty)
.AfterMap((source, target) => target.FullName = $"{source.Name} {source.Surname}")
.AfterMap((source, target) => target.Email = target.Email.Trim().ToLowerInvariant());
Si el mapeo es completamente específico, puedes sustituirlo por código manual:
configuration.CreateMap<UserEntity, UserDto>()
.MapUsing(source => new UserDto
{
Id = source.Id,
FullName = $"{source.Name} {source.Surname}"
});
Para updates explícitos:
configuration.CreateMap<UpdateUserDto, UserEntity>()
.MapIntoUsing((source, target) =>
{
if (source.Name is not null)
{
target.Name = source.Name;
}
});
NullPathBehavior
Por defecto, FromPath(...) y MapFromPathAttribute usan NullPathBehavior.Skip.
var configuration = new ObjectMappingConfiguration()
.ConfigureOptions(options =>
{
options.NullPathBehavior = ObjectMappingNullPathBehavior.Throw;
});
Valores disponibles:
Skip: conserva el valor actual del destinoAssign: asignanullsi el destino lo admiteThrow: falla cuando un segmento anidado esnull
Validación
configuration.Validate();
configuration.Validate(ObjectMappingValidationMode.AllWritableDestinationMembers);
configuration.ValidateMap<CustomerEntity, CustomerDto>();
configuration.ValidateConventionMap<CustomerEntity, CustomerDto>();
Si necesitas datos estructurados de validación sin lanzar excepción:
var errors = configuration.GetValidationErrors();
var customerErrors = configuration.GetValidationErrors<CustomerEntity, CustomerDto>();
var conventionError = configuration.GetConventionValidationError<CustomerEntity, CustomerDto>();
var registeredMaps = configuration.GetRegisteredMaps();
GetValidationErrors<TSource, TTarget>() inspecciona solo mapas explícitamente registrados.
Si necesitas validar por convención o atributos un par de tipos sin configuración explícita, usa GetConventionValidationError<TSource, TTarget>().
Usa validación en estos escenarios:
- comprobaciones de startup antes de atender peticiones
- tests de contrato de mapeo en CI
- flujos de precompilación
- módulos que registran perfiles dinámicamente
Cuando una ruta anidada es inválida, los errores estructurados incluyen la ruta original:
var errors = configuration.GetValidationErrors<OrderEntity, OrderDto>();
if (errors.Count > 0)
{
var error = errors[0];
Console.WriteLine(error.Kind);
Console.WriteLine(error.SourcePath);
}
Ejemplo típico de tratamiento estructurado:
var errors = configuration.GetValidationErrors();
foreach (var error in errors)
{
Console.WriteLine($"{error.Kind} | {error.SourceType.Name} -> {error.TargetType.Name}");
Console.WriteLine(error.Message);
}
Descriptores de mapas para tooling y diagnóstico
La configuración runtime puede exponer metadatos de los mapas explícitos sin depender de cachés internas ni delegates:
var descriptors = configuration.GetMapDescriptors();
var customerMap = configuration.GetMapDescriptor<CustomerEntity, CustomerDto>();
if (configuration.TryGetMapDescriptor<CustomerEntity, CustomerDto>(out var descriptor))
{
var targetMembers = descriptor.Members.Select(member => member.TargetMember).ToArray();
}
También puedes inspeccionar cómo se resuelve cada miembro:
foreach (var member in customerMap.Members)
{
Console.WriteLine($"{member.TargetMember} <- {member.SourcePath ?? member.SourceMember} ({member.SourceKind})");
}
Los descriptores son útiles para:
- diagnóstico y reporting en startup
- tooling personalizado
- generación de documentación
- mantener visible la configuración runtime para paquetes complementarios
Alcance de los descriptores runtime:
- describen configuración explícita registrada en runtime
- no expanden miembros resueltos solo por convención
- no exponen delegates compilados ni estructuras internas de caché
- ofrecen una superficie estable para diagnóstico y tooling complementario
Si necesitas inspeccionar el contrato efectivo por convención y atributos para un par de tipos, usa:
var conventionDescriptor = configuration.GetConventionMapDescriptor<CustomerEntity, CustomerDto>();
if (configuration.TryGetConventionMapDescriptor<CustomerEntity, CustomerDto>(out var descriptor))
{
var members = descriptor.Members.Select(member => member.TargetMember).ToArray();
}
Si necesitas el descriptor que el motor usará realmente en runtime, pide el mapa efectivo:
var effectiveDescriptor = configuration.GetEffectiveMapDescriptor<CustomerEntity, CustomerDto>();
Esto resulta especialmente útil cuando quieres saber si runtime usará:
- un mapa fluido explícito
- atributos
- o pura convención
Guía rápida de selección de descriptores:
| API | Cuándo usarla | Notas |
|---|---|---|
GetMapDescriptor |
cuando quieres solo la configuración fluida/perfil registrada | UsesExplicitConfiguration es true |
GetConventionMapDescriptor |
cuando quieres el contrato por convención y atributos de un par de tipos | ignora reglas fluidas explícitas |
GetEffectiveMapDescriptor |
cuando quieres saber qué usará realmente el motor en runtime | si existe mapa explícito, tiene prioridad; si no, cae a convención |
Tipos de descriptor:
ExplicitConfigurationConventionContractEffectiveRuntimeMap
Orígenes posibles de los miembros:
ExplicitMemberExplicitPathExplicitIgnoreAttributeMapFromAttributeMapFromPathAttributeIgnoreGlobalIgnoreConventionUnresolved
Nota de rendimiento para tooling:
- las APIs de descriptores están pensadas para diagnóstico de startup, reporting y tooling complementario
- se cachean por versión de configuración, así que lecturas repetidas son baratas
- las APIs de validación siguen siendo más costosas que la introspección y conviene dejarlas fuera del hot path
Precompilación
Los mapas configurados y por convención se compilan de forma lazy en el primer uso. Si quieres eliminar la latencia del primer acceso en aplicaciones backend, puedes precompilarlos durante el arranque:
configuration.CompileMaps();
configuration.CompileMaps(descriptor => descriptor.ProfileType == typeof(CustomerProfile));
configuration.CompileMapsForProfile<CustomerProfile>();
configuration.CompileMapsFromAssembly(typeof(CustomerProfile).Assembly);
configuration.CompileMap<CustomerEntity, CustomerDto>();
configuration.CompileConventionMap<CustomerEntity, CustomerDto>();
Flujo típico de startup:
configuration.Validate();
configuration.CompileMapsForProfile<CustomerProfile>();
La precompilación es útil cuando:
- la aplicación tiene un conjunto estable de mapas conocidos
- importa que la primera petición tenga una latencia predecible
- quieres absorber en el startup el coste de compilar delegates
Integración con Pitasoft.DataAccess
Patrón recomendado:
Pitasoft.DataAccessmaterializa entidadesPitasoft.ObjectMappinglas transforma en memoriaPitasoft.Resultrepresenta éxito y errorPitasoft.Result.AspNetCoretraduce resultados a respuestas HTTP
Lectura típica:
var customer = await repository.GetByIdAsync(id, cancellationToken);
var dto = customer.MapTo<CustomerEntity, CustomerDto>(configuration);
Actualización típica:
var customer = await repository.GetByIdAsync(id, cancellationToken);
updateDto.MapInto(customer, configuration);
await repository.SaveChangesAsync(cancellationToken);
Patrón recomendado de servicio:
public sealed class CustomerApplicationService
{
private readonly ICustomerRepository _repository;
private readonly ObjectMappingConfiguration _mapping;
public CustomerApplicationService(
ICustomerRepository repository,
ObjectMappingConfiguration mapping)
{
_repository = repository;
_mapping = mapping;
}
public async Task<CustomerDto?> GetAsync(Guid id, CancellationToken cancellationToken)
{
var entity = await _repository.GetByIdAsync(id, cancellationToken);
return entity?.MapTo<CustomerEntity, CustomerDto>(_mapping);
}
public async Task UpdateAsync(Guid id, UpdateCustomerDto request, CancellationToken cancellationToken)
{
var entity = await _repository.GetByIdAsync(id, cancellationToken)
?? throw new InvalidOperationException("Customer not found.");
request.MapInto(entity, _mapping);
await _repository.SaveChangesAsync(cancellationToken);
}
}
Notas
MapTocrea una nueva instancia destinoMapIntoactualiza una instancia destino existenteNullPathBehaviorpor defecto esSkip- para updates backend,
IgnoreNullValues = truesuele ser la opción más segura - cuando el mapeo forma parte del contrato de la aplicación, es mejor usar configuración fluida que atributos
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.