Pitasoft.ObjectMapping
1.0.1
See the version list below for details.
dotnet add package Pitasoft.ObjectMapping --version 1.0.1
NuGet\Install-Package Pitasoft.ObjectMapping -Version 1.0.1
<PackageReference Include="Pitasoft.ObjectMapping" Version="1.0.1" />
<PackageVersion Include="Pitasoft.ObjectMapping" Version="1.0.1" />
<PackageReference Include="Pitasoft.ObjectMapping" />
paket add Pitasoft.ObjectMapping --version 1.0.1
#r "nuget: Pitasoft.ObjectMapping, 1.0.1"
#:package Pitasoft.ObjectMapping@1.0.1
#addin nuget:?package=Pitasoft.ObjectMapping&version=1.0.1
#tool nuget:?package=Pitasoft.ObjectMapping&version=1.0.1
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 |
| Collections | MapListTo, MapArrayTo |
| Attributes | MapFrom, MapFromPath, MapIgnore |
| Fluent configuration | ObjectMappingConfiguration, CreateMap, ToMember, FromMember, FromPath, Ignore |
| Profiles | IObjectMappingProfile, ObjectMappingProfile, AddProfile, AddProfilesFromAssemblies |
| Validation | Validate, ValidateMap, ObjectMappingValidationMode |
| Customization | BeforeMap, AfterMap, MapUsing, MapIntoUsing |
| Options | IgnoreNullValues, NullPathBehavior, IgnoreDestinationMembers, UseAuditableMemberStrategy |
| Service facade | IObjectMapper, ObjectMapper |
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
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");
Collection mapping
var list = users.MapListTo<UserEntity, UserDto>();
var array = users.MapArrayTo<UserEntity, UserDto>();
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;
}
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; }
}
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;
}
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);
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);
Update DTO → Entity with ignored nulls
var configuration = new ObjectMappingConfiguration()
.ConfigureOptions(options =>
{
options.IgnoreNullValues = true;
options.UseAuditableMemberStrategy(ObjectMappingAuditableMemberStrategy.IgnoreCommonMembers);
});
updateDto.MapInto(entity, configuration);
Global converter
var configuration = new ObjectMappingConfiguration()
.AddConverter<string, int>(value => int.Parse(value));
Member-specific converter
configuration.CreateMap<ExternalCustomer, ExternalCustomerDto>()
.ToMember(target => target.Id)
.FromMember(source => source.Identifier, value => int.Parse(value));
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());
Manual customization
configuration.CreateMap<UserEntity, UserDto>()
.AfterMap((source, target) => target.FullName = $"{source.Name} {source.Surname}");
Manual factory
configuration.CreateMap<UserEntity, UserDto>()
.MapUsing(source => new UserDto
{
Id = source.Id,
FullName = $"{source.Name} {source.Surname}"
});
Manual update
configuration.CreateMap<UpdateUserDto, UserEntity>()
.MapIntoUsing((source, target) =>
{
if (source.Name is not null)
{
target.Name = source.Name;
}
});
Validation
configuration.Validate();
configuration.Validate(ObjectMappingValidationMode.AllWritableDestinationMembers);
configuration.ValidateMap<CustomerEntity, CustomerDto>();
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);
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 |
| Colecciones | MapListTo, MapArrayTo |
| Atributos | MapFrom, MapFromPath, MapIgnore |
| Configuración fluida | ObjectMappingConfiguration, CreateMap, ToMember, FromMember, FromPath, Ignore |
| Perfiles | IObjectMappingProfile, ObjectMappingProfile, AddProfile, AddProfilesFromAssemblies |
| Validación | Validate, ValidateMap, ObjectMappingValidationMode |
| Personalización | BeforeMap, AfterMap, MapUsing, MapIntoUsing |
| Opciones | IgnoreNullValues, NullPathBehavior, IgnoreDestinationMembers, UseAuditableMemberStrategy |
| Fachada de servicio | IObjectMapper, ObjectMapper |
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
var dto = entity.MapTo<Entity, EntityDto>();
entity.MapInto(existingDto);
var selected = entity.MapMembersTo<Entity, EntityDto>("Id", "Name");
var list = entities.MapListTo<Entity, EntityDto>();
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);
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);
Update parcial con nulos ignorados
var configuration = new ObjectMappingConfiguration()
.ConfigureOptions(options =>
{
options.IgnoreNullValues = true;
options.UseAuditableMemberStrategy(ObjectMappingAuditableMemberStrategy.IgnoreCommonMembers);
});
updateDto.MapInto(entity, configuration);
Validación
configuration.Validate();
configuration.Validate(ObjectMappingValidationMode.AllWritableDestinationMembers);
configuration.ValidateMap<CustomerEntity, CustomerDto>();
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);
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 © 2021-2026 Pitasoft, S.L.
Licenciado bajo los términos de la LICENCE.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.