Pitasoft.ObjectMapping 1.0.1

There is a newer version of this package available.
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
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Pitasoft.ObjectMapping" Version="1.0.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Pitasoft.ObjectMapping" Version="1.0.1" />
                    
Directory.Packages.props
<PackageReference Include="Pitasoft.ObjectMapping" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Pitasoft.ObjectMapping --version 1.0.1
                    
#r "nuget: Pitasoft.ObjectMapping, 1.0.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Pitasoft.ObjectMapping@1.0.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Pitasoft.ObjectMapping&version=1.0.1
                    
Install as a Cake Addin
#tool nuget:?package=Pitasoft.ObjectMapping&version=1.0.1
                    
Install as a Cake Tool

Pitasoft.ObjectMapping

NuGet Version NuGet Downloads License .NET

English | Castellano


English

Pitasoft.ObjectMapping is a .NET library for backend object mapping.

It is designed for scenarios such as:

  • Entity -> DTO
  • DTO -> 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:

  1. fluent configuration
  2. MapFromAttribute
  3. MapFromPathAttribute
  4. direct member name match

General rules:

  • destination members must be writable
  • source members must be readable
  • mapping is shallow unless FromPath(...) or MapFromPathAttribute is 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:

  • ConfiguredMembersOnly
  • AllWritableDestinationMembers

Pitasoft.DataAccess Integration

Recommended pattern:

  • Pitasoft.DataAccess materializes entities
  • Pitasoft.ObjectMapping transforms them in memory
  • Pitasoft.Result represents success and failure
  • Pitasoft.Result.AspNetCore translates 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

  • MapTo creates a new destination instance
  • MapInto updates an existing destination instance
  • NullPathBehavior defaults to Skip
  • for backend updates, IgnoreNullValues = true is 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 -> DTO
  • DTO -> 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:

  1. configuración fluida
  2. MapFromAttribute
  3. MapFromPathAttribute
  4. 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(...) o MapFromPathAttribute
  • 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.DataAccess materializa entidades
  • Pitasoft.ObjectMapping las transforma en memoria
  • Pitasoft.Result representa éxito y error
  • Pitasoft.Result.AspNetCore traduce 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

  • MapTo crea una nueva instancia destino
  • MapInto actualiza una instancia destino existente
  • NullPathBehavior por defecto es Skip
  • para updates backend, IgnoreNullValues = true suele 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 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • 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.

Version Downloads Last Updated
1.1.1 213 4/17/2026
1.0.2 156 4/12/2026
1.0.1 145 4/10/2026