Pitasoft.ObjectMapping.Generator 1.0.1

dotnet add package Pitasoft.ObjectMapping.Generator --version 1.0.1
                    
NuGet\Install-Package Pitasoft.ObjectMapping.Generator -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.Generator" Version="1.0.1">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Pitasoft.ObjectMapping.Generator" Version="1.0.1" />
                    
Directory.Packages.props
<PackageReference Include="Pitasoft.ObjectMapping.Generator">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
                    
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.Generator --version 1.0.1
                    
#r "nuget: Pitasoft.ObjectMapping.Generator, 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.Generator@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.Generator&version=1.0.1
                    
Install as a Cake Addin
#tool nuget:?package=Pitasoft.ObjectMapping.Generator&version=1.0.1
                    
Install as a Cake Tool

Pitasoft.ObjectMapping.Generator

NuGet Version NuGet Downloads License .NET

English | Castellano


English

Pitasoft.ObjectMapping.Generator is a Roslyn source generator for compile-time object mapping.

It generates mapper implementations from partial classes marked with [ObjectMapper] and is designed for scenarios that want:

  • zero runtime reflection in hot paths
  • AOT-friendly mapping code
  • compile-time generated MapTo, MapInto, MapListTo, and MapArrayTo
  • support for MapFrom, MapFromPath, and MapIgnore
  • automatic mapping through inheritance, interfaces, and enum types
  • collection property mapping (List<A> to List<B>, A[] to B[])

Installation

dotnet add package Pitasoft.ObjectMapping
dotnet add package Pitasoft.ObjectMapping.Generator

NuGet-Ready Quick Start

Copy/paste this flow in a clean project:

  1. Install packages:
dotnet add package Pitasoft.ObjectMapping
dotnet add package Pitasoft.ObjectMapping.Generator
  1. Create source and destination models:
public sealed class UserEntity
{
    public Guid Id { get; set; }
    public string Name { get; set; } = "";
    public string Email { get; set; } = "";
}

public sealed class UserDto
{
    public Guid Id { get; set; }
    public string Name { get; set; } = "";
    public string Email { get; set; } = "";
}
  1. Add a mapper:
using Pitasoft.ObjectMapping;

[ObjectMapper]
public partial class UserMapper
{
    public partial UserDto MapTo(UserEntity source);
}
  1. Build the project. The implementation is generated at compile time.

  2. Use the mapper:

var mapper = new UserMapper();
var dto = mapper.MapTo(new UserEntity
{
    Id = Guid.NewGuid(),
    Name = "Ada",
    Email = "ada@domain.test"
});

Practical Recipes (Detailed)

These recipes focus on common production scenarios.

Recipe 1: DTO Create + Update (MapTo + MapInto)

Use MapTo for read models and MapInto for updating existing objects.

public sealed class ProductEntity
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public decimal Price { get; set; }
    public string InternalCode { get; set; } = "";
}

public sealed class ProductDto
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public decimal Price { get; set; }
}

[ObjectMapper]
public partial class ProductMapper
{
    public partial ProductDto MapTo(ProductEntity source);
    public partial void MapInto(ProductEntity source, ProductDto target);
}
var mapper = new ProductMapper();
var dto = mapper.MapTo(entity);
mapper.MapInto(entity, dto); // updates same instance
Recipe 2: CQRS Query Projection (ProjectTo)

Use ProjectTo when querying with IQueryable providers (for example EF Core).

using System.Linq.Expressions;
using Pitasoft.ObjectMapping;
using Pitasoft.ObjectMapping.Attributes;

public sealed class OrderEntity
{
    public int Id { get; set; }
    public CustomerEntity? Customer { get; set; }
    public decimal Total { get; set; }
    public decimal Discount { get; set; }
}

public sealed class CustomerEntity
{
    public string Name { get; set; } = "";
}

public sealed class OrderListItemDto
{
    public int Id { get; set; }
    [MapFromPath("Customer.Name")]
    public string? CustomerName { get; set; }
    [MapCondition("ShouldMapDiscount")]
    public decimal Discount { get; set; } = 0m;
    public decimal Total { get; set; }
}

[ObjectMapper]
public partial class OrderQueryMapper
{
    public partial Expression<Func<OrderEntity, OrderListItemDto>> ProjectTo();
    public bool ShouldMapDiscount(OrderEntity s) => s.Discount > 0;
}
var mapper = new OrderQueryMapper();
var query = dbContext.Orders.Select(mapper.ProjectTo());
var items = await query.ToListAsync(ct);

Recommendation:

  • Keep projection logic simple and provider-friendly.
  • If the provider cannot translate a piece of logic, materialize first and then use MapTo.
Recipe 3: API Layer Write Model (MapInto + null-safe updates)

Useful for PATCH-like updates where null values should not overwrite destination values.

public sealed class UpdateUserRequest
{
    public string? Name { get; set; }
    public string? Phone { get; set; }
}

public sealed class UserEntity
{
    public Guid Id { get; set; }
    public string Name { get; set; } = "";
    public string Phone { get; set; } = "";
}

[ObjectMapper(IgnoreNullValues = true)]
public partial class UserWriteMapper
{
    public partial void MapInto(UpdateUserRequest source, UserEntity target);
}
var mapper = new UserWriteMapper();
mapper.MapInto(request, entity); // null request fields are skipped
Recipe 4: Custom field + conditional mapping

Combine [MapCustom] and [MapCondition] for expressive mapping.

using Pitasoft.ObjectMapping.Attributes;

public sealed class InvoiceEntity
{
    public string Number { get; set; } = "";
    public string CustomerName { get; set; } = "";
    public decimal Discount { get; set; }
}

public sealed class InvoiceDto
{
    [MapCustom("BuildDisplayName")]
    public string DisplayName { get; set; } = "";

    [MapCondition("ShouldMapDiscount")]
    public decimal Discount { get; set; } = 0m;
}

[ObjectMapper]
public partial class InvoiceMapper
{
    public partial InvoiceDto MapTo(InvoiceEntity source);

    public string BuildDisplayName(InvoiceEntity s) => $"{s.Number} - {s.CustomerName}";
    public bool ShouldMapDiscount(InvoiceEntity s) => s.Discount > 0;
}
Recipe 5: Flattening + explicit paths for nested graphs
public sealed class CustomerEntity
{
    public AddressEntity? Address { get; set; }
}

public sealed class AddressEntity
{
    public string City { get; set; } = "";
    public CountryEntity? Country { get; set; }
}

public sealed class CountryEntity
{
    public string Iso2 { get; set; } = "";
}

public sealed class CustomerDto
{
    // Auto-flattening: AddressCity <- Address.City
    public string? AddressCity { get; set; }

    [MapFromPath("Address.Country.Iso2")]
    public string? CountryCode { get; set; }
}

[ObjectMapper]
public partial class CustomerMapper
{
    public partial CustomerDto MapTo(CustomerEntity source);
}

NuGet Publication Checklist

Use this checklist before pushing a new package release:

  1. Version and changelog are updated.
  2. README.md examples compile against current API.
  3. dotnet test passes for all target frameworks.
  4. Diagnostics section includes all active IDs (currently PMAP001-PMAP013).
  5. Repository links and package metadata are valid.
  6. Comparison/performance notes reflect current behavior (especially projection caveats).

Basic Usage

using Pitasoft.ObjectMapping;

[ObjectMapper]
public partial class CustomerMapper
{
    public partial CustomerDto MapTo(CustomerEntity source);
    public partial void MapInto(CustomerEntity source, CustomerDto target);
    public partial List<CustomerDto> MapListTo(IEnumerable<CustomerEntity> source);
    public partial CustomerDto[] MapArrayTo(IEnumerable<CustomerEntity> source);
}

The generator produces the implementation at compile time.

Run The Included Examples In This Repository

This solution already includes runnable projects so you can validate behavior quickly:

# Console sample with mapping scenarios
dotnet run --project Pitasoft.ObjectMapping.Generator.Example/Pitasoft.ObjectMapping.Generator.Example.csproj

# Benchmark suite (manual vs generated vs other mappers)
dotnet run -c Release --project Pitasoft.ObjectMapping.Generator.Benchmarks/Pitasoft.ObjectMapping.Generator.Benchmarks.csproj

End-To-End Detailed Example

The following example combines convention mapping, flattening, MapFromPath, MapCustom, MapCondition, BeforeMap, AfterMap, and projection in a single mapper.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Pitasoft.ObjectMapping;
using Pitasoft.ObjectMapping.Attributes;

public sealed class CustomerEntity
{
    public int Id { get; set; }
    public string FirstName { get; set; } = "";
    public string LastName { get; set; } = "";
    public bool IsActive { get; set; }
    public DateTime CreatedAt { get; set; }
    public AddressEntity? Address { get; set; }
    public decimal Discount { get; set; }
}

public sealed class AddressEntity
{
    public string City { get; set; } = "";
    public CountryEntity? Country { get; set; }
}

public sealed class CountryEntity
{
    public string Code { get; set; } = "";
}

public sealed class CustomerDto
{
    [MapFrom("Id")]
    public int CustomerId { get; set; }

    // Convention map
    public bool IsActive { get; set; }

    // Flattening by name: AddressCity <- Address.City
    public string? AddressCity { get; set; }

    // Explicit path map
    [MapFromPath("Address.Country.Code")]
    public string? CountryCode { get; set; }

    [MapCustom("ComputeFullName")]
    public string FullName { get; set; } = "";

    [MapCondition("ShouldMapDiscount")]
    public decimal Discount { get; set; } = -1m;

    [MapIgnore]
    public string? InternalComment { get; set; }
}

[ObjectMapper(IgnoreNullValues = true, CaseInsensitiveMatching = true)]
public partial class CustomerMapper
{
    public partial CustomerDto MapTo(CustomerEntity source);
    public partial void MapInto(CustomerEntity source, CustomerDto target);
    public partial List<CustomerDto> MapListTo(IEnumerable<CustomerEntity> source);
    public partial CustomerDto[] MapArrayTo(IEnumerable<CustomerEntity> source);
    public partial Expression<Func<CustomerEntity, CustomerDto>> ProjectTo();

    public string ComputeFullName(CustomerEntity source) => $"{source.FirstName} {source.LastName}";
    public bool ShouldMapDiscount(CustomerEntity source) => source.Discount > 0;

    public void BeforeMap(CustomerEntity source, CustomerDto target)
    {
        // Runs before generated property assignments in MapTo/MapInto.
        target.InternalComment = "initialized";
    }

    public void AfterMap(CustomerEntity source, CustomerDto target)
    {
        // Runs after generated property assignments in MapTo/MapInto.
        if (!target.IsActive)
            target.InternalComment = "inactive";
    }
}

Usage:

var mapper = new CustomerMapper();

var entity = new CustomerEntity
{
    Id = 7,
    FirstName = "Ada",
    LastName = "Lovelace",
    IsActive = true,
    Discount = 10,
    Address = new AddressEntity
    {
        City = "London",
        Country = new CountryEntity { Code = "UK" }
    }
};

// Create
var dto = mapper.MapTo(entity);

// Update existing
mapper.MapInto(entity, dto);

// Bulk
var list = mapper.MapListTo(new[] { entity });
var array = mapper.MapArrayTo(new[] { entity });

// IQueryable projection
var projected = new[] { entity }.AsQueryable().Select(mapper.ProjectTo()).ToList();

Dependency Injection Registration (Optional)

If you also install Pitasoft.ObjectMapping.Generator.DependencyInjectionExtensions:

using System.Reflection;
using Pitasoft.ObjectMapping.Generator.DependencyInjectionExtensions;

var services = new ServiceCollection();

// Register all mappers from one or more assemblies
services.AddObjectMappers(Assembly.GetExecutingAssembly());

// Or register one mapper explicitly
services.AddObjectMapper<CustomerMapper>();

Projection Notes (ProjectTo)

  • ProjectTo returns Expression<Func<TSource, TTarget>>.
  • This is intended for IQueryable providers (for example EF Core).
  • For full server-side translation, custom/conditional logic must be provider-translatable.
  • MapCondition is inlined into the projection when possible (for example s => s.Discount > 0).
  • If MapCondition cannot be inlined, or if the inlined condition calls a helper method on the mapper, the generator emits PMAP013 so you can review SQL translatability risk.
  • If your provider cannot translate a part of the expression, use MapTo after materialization (ToList()), or simplify the projection logic.

Convention-Based Mapping

public sealed class SimpleSource
{
    public int Id { get; set; }
    public string Value { get; set; } = string.Empty;
}

public sealed class SimpleTarget
{
    public int Id { get; set; }
    public string Value { get; set; } = string.Empty;
}

[ObjectMapper]
public partial class SimpleMapper
{
    public partial SimpleTarget MapTo(SimpleSource source);
    public partial void MapInto(SimpleSource source, SimpleTarget target);
}

MapFrom

using Pitasoft.ObjectMapping.Attributes;

public sealed class CustomerDto
{
    [MapFrom("Id")]
    public int CustomerId { get; set; }

    public string Name { get; set; } = string.Empty;
}

MapFromPath

using Pitasoft.ObjectMapping.Attributes;

public sealed class CustomerDto
{
    [MapFromPath("Address.City")]
    public string? City { get; set; }

    [MapFromPath("Address.Country.Code")]
    public string? CountryCode { get; set; }
}

Generated path access is null-safe. If an intermediate node is null, the generated code returns null for that destination member.

MapIgnore

using Pitasoft.ObjectMapping.Attributes;

public sealed class CustomerDto
{
    public int CustomerId { get; set; }

    [MapIgnore]
    public string? ComputedField { get; set; }
}

Ignore null values in MapInto

[ObjectMapper(IgnoreNullValues = true)]
public partial class NullSafeMapper
{
    public partial void MapInto(CustomerEntity source, CustomerDto target);
}

With IgnoreNullValues = true, generated MapInto methods skip null source values instead of overwriting the target.

Matching options

[ObjectMapper(
    CaseInsensitiveMatching = true,
    SourcePrefixToIgnore = "Db",
    TargetPrefixToIgnore = "Customer")]
public partial class FlexibleMapper
{
    public partial CustomerDto MapTo(CustomerEntity source);
}

Use these options to adapt convention matching in heterogeneous models.

Supported Partial Method Shapes

Method Signature
MapTo TTarget MapTo(TSource source)
MapInto void MapInto(TSource source, TTarget target)
MapListTo List<TTarget> MapListTo(IEnumerable<TSource> source)
MapArrayTo TTarget[] MapArrayTo(IEnumerable<TSource> source)
ProjectTo Expression<Func<TSource, TTarget>> ProjectTo()
TryMapTo bool TryMapTo(TSource source, out TTarget target)
TryMapInto bool TryMapInto(TSource source, TTarget target)

MapListTo also supports these return types: IEnumerable<T>, ICollection<T>, IList<T>, IReadOnlyCollection<T>, IReadOnlyList<T>.

Enum Mapping

The generator supports mapping between different enum types with the same underlying values. An explicit cast is emitted automatically:

public enum StatusEntity { Active, Inactive }
public enum StatusDto { Active, Inactive }

public sealed class OrderEntity { public StatusEntity Status { get; set; } }
public sealed class OrderDto { public StatusDto Status { get; set; } }

[ObjectMapper]
public partial class OrderMapper
{
    public partial OrderDto MapTo(OrderEntity source);
}
// Generated: Status = (StatusDto)source.Status

Collection Property Mapping

When a source property is a collection of type A and the target expects a collection of type B, the generator maps elements individually using LINQ:

public sealed class OrderEntity
{
    public List<OrderLineEntity> Lines { get; set; }
}

public sealed class OrderDto
{
    public List<OrderLineDto> Lines { get; set; }
}

[ObjectMapper]
public partial class OrderMapper
{
    public partial OrderDto MapTo(OrderEntity source);
}
// Generated: Lines = source.Lines.Select(x => new OrderLineDto { ... }).ToList()

Supported collection shapes: List<T>, IEnumerable<T>, ICollection<T>, IList<T>, IReadOnlyList<T>, IReadOnlyCollection<T>, HashSet<T>, ISet<T>, IReadOnlySet<T>, LinkedList<T>, ImmutableList<T>, ImmutableArray<T>, ImmutableHashSet<T>, Dictionary<K,V>, and T[]. Nested collections (List<List<T>>) are also supported.

Auto-Flattening

Target properties whose names concatenate nested source paths are automatically resolved:

public class Source { public Address? Address { get; set; } }
public class Address { public string City { get; set; } = ""; }
public class Target { public string? AddressCity { get; set; } } // auto-resolved to source.Address?.City

MapCustom

Delegate a target property to a custom method on the mapper:

using Pitasoft.ObjectMapping.Attributes;

public class Target
{
    [MapCustom("ComputeFullName")]
    public string FullName { get; set; } = "";
}

[ObjectMapper]
public partial class MyMapper
{
    public partial Target MapTo(Source source);
    public string ComputeFullName(Source s) => $"{s.FirstName} {s.LastName}";
}

MapCondition

Conditionally map a property based on a bool method:

using Pitasoft.ObjectMapping.Attributes;

public class Target
{
    [MapCondition("ShouldMapDiscount")]
    public decimal Discount { get; set; }
}

[ObjectMapper]
public partial class MyMapper
{
    public partial void MapInto(Source source, Target target);
    public bool ShouldMapDiscount(Source s) => s.Discount > 0;
}

For ProjectTo (Expression<Func<S,T>>), condition/custom methods must be translatable by your LINQ provider to remain fully server-side. If the generator detects non-translatable risk in projection (MapCustom, non-inlineable condition, or inlined condition calling mapper helpers), it reports PMAP013.

AfterMap Hook

Define an AfterMap method to run custom logic after mapping:

[ObjectMapper]
public partial class MyMapper
{
    public partial Target MapTo(Source source);
    public void AfterMap(Source s, Target t) { t.FullName = $"{s.First} {s.Last}"; }
}

String ↔ Enum

// string → enum: uses Enum.Parse<T>()
// enum → string: uses .ToString()
public class Source { public string Status { get; set; } = "Active"; }
public class Target { public StatusEnum Status { get; set; } }

Nullable Unwrapping

Nullable<T> → T automatically uses .GetValueOrDefault():

public class Source { public int? Score { get; set; } }
public class Target { public int Score { get; set; } } // source.Score.GetValueOrDefault()

DateTime ↔ DateOnly / TimeOnly

Automatic conversions between temporal types:

  • DateTime → DateOnly via DateOnly.FromDateTime()
  • DateTime → TimeOnly via TimeOnly.FromDateTime()
  • DateOnly → DateTime via .ToDateTime(TimeOnly.MinValue)
  • TimeOnly ↔ TimeSpan

Conversion Operators

Implicit and explicit conversion operators are detected and used automatically via cast.

StrictMapping

[ObjectMapper(StrictMapping = true)]
public partial class StrictMapper
{
    public partial Target MapTo(Source source);
}
// Unmapped properties emit PMAP010 warning instead of PMAP004 info

TryMapTo / TryMapInto

Safe mapping that catches exceptions and returns bool:

[ObjectMapper]
public partial class SafeMapper
{
    public partial bool TryMapTo(Source source, out Target target);
    public partial bool TryMapInto(Source source, Target target);
}

// Usage
if (mapper.TryMapTo(source, out var target))
{
    // mapping succeeded
}

Returns false when source/target is null or any exception occurs.

EnumMappingStrategy

Control how enum-to-enum mappings are generated:

// ByValue (default): uses explicit cast — (TargetEnum)source.Status
[ObjectMapper(EnumMappingStrategy = 0)]
public partial class ByValueMapper { ... }

// ByName: uses Enum.Parse — Enum.Parse<TargetEnum>(source.Status.ToString())
[ObjectMapper(EnumMappingStrategy = 1)]
public partial class ByNameMapper { ... }

IgnoreMembers / IgnoreAuditableMembers

Globally ignore properties by name without adding [MapIgnore] to each:

// Ignore specific members
[ObjectMapper(IgnoreMembers = "Secret,Internal,TempField")]
public partial class MyMapper { ... }

// Ignore common audit properties (Id, CreatedAt, UpdatedAt, CreatedBy, etc.)
[ObjectMapper(IgnoreAuditableMembers = true)]
public partial class WriteMapper { ... }

IgnoreAuditableMembers auto-ignores: Id, CreatedAt, CreatedOn, UpdatedAt, UpdatedBy, ModifiedAt, DeletedAt, RowVersion, ConcurrencyStamp, and more.

NullPathBehavior

Control behavior when a nested path resolves to null:

// Skip (default): uses ?. navigation, null propagates silently
[ObjectMapper(NullPathBehavior = 0)]

// Throw: uses direct . navigation, throws NullReferenceException if intermediate is null
[ObjectMapper(NullPathBehavior = 2)]

BeforeMap Hook

Define a BeforeMap method to run custom logic before mapping:

[ObjectMapper]
public partial class MyMapper
{
    public partial Target MapTo(Source source);
    public void BeforeMap(Source s, Target t) { t.Timestamp = DateTime.UtcNow; }
}

String ↔ Numeric

Automatic parsing between string and numeric types:

// string → int: uses int.Parse(source.Count, CultureInfo.InvariantCulture)
// string → decimal, double, float, long, short, byte, bool
// int → string: uses .ToString()
public class Source { public string Count { get; set; } = "42"; }
public class Target { public int Count { get; set; } }

Collection Type Conversion (Same Element)

When source and target are different collection types with the same element:

public class Source { public List<int> Tags { get; set; } }
public class Target { public HashSet<int> Tags { get; set; } }
// Generated: Tags = source.Tags.ToHashSet()

// Also supports: List→Array, List→LinkedList, HashSet→List, etc.

Record Struct

Record structs are fully supported with value-type optimizations (no null guards):

public record struct PointSource(int X, int Y);
public record struct PointTarget(int X, int Y);

[ObjectMapper]
public partial class PointMapper
{
    public partial PointTarget MapTo(PointSource source);
}

Minimal API Integration (Pitasoft Ecosystem)

When used with Pitasoft.Result, Pitasoft.Result.AspNetCore, and Pitasoft.DataAccess:

using Pitasoft.Result;
using Pitasoft.Result.AspNetCore.Extensions;
using Pitasoft.Result.AspNetCore.Parameters;
using Pitasoft.DataAccess;
using Pitasoft.ObjectMapping.Generator.DependencyInjectionExtensions;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddResultAspNetCore();
builder.Services.AddObjectMappers(typeof(ProductMapper).Assembly);

var api = app.MapGroup("").AddResultFilter();

// GET with filtering, sorting, paging, field selection
api.MapGet("/products", (AppDbContext db, ProductMapper mapper, EntityParameters p) =>
{
    var query = db.Products.AsQueryable()
        .ApplyFilter(p.Query)
        .ApplySearch(p.Search, "Name", "Description")
        .ApplySort(p.Order);

    if (p.Page.HasValue)
        return query.Select(mapper.ProjectTo()).ToResultPaged(p.Page ?? 1, p.PageSize ?? 10);

    return mapper.MapSummaryList(query.ToList()).ToOkResult() as IResult;
});

// GET by id
api.MapGet("/products/{id}", async (int id, AppDbContext db, ProductMapper mapper) =>
{
    var entity = await db.Products.FindAsync(id);
    if (entity is null) return StatusResult.NotFound;
    return mapper.MapTo(entity).ToOkResult();
});

// POST
api.MapPost("/products", async (CreateRequest req, AppDbContext db, ProductMapper mapper) =>
{
    var entity = mapper.MapTo(req);
    db.Products.Add(entity);
    await db.SaveChangesAsync();
    return entity.Id.ToAddedResult();
});

// PATCH (only non-null fields applied)
api.MapPatch("/products/{id}", async (int id, PatchRequest req, AppDbContext db, PatchMapper mapper) =>
{
    var entity = await db.Products.FindAsync(id);
    if (entity is null) return new Result(StatusResult.NotFound);
    mapper.MapInto(req, entity);  // IgnoreNullValues = true
    await db.SaveChangesAsync();
    return new Result(StatusResult.Updated);
});

Type Compatibility

The generator supports the following type mappings:

  • Exact match — same type on source and target
  • Nullable widening — T to T?
  • Nullable unwrapping — T? to T via .GetValueOrDefault()
  • Inheritance — derived class to base class
  • Interface implementation — e.g. List<T> to IEnumerable<T>
  • Enum-to-enum — different enum types via explicit cast
  • String ↔ Enum — Enum.Parse<T>() / .ToString()
  • DateTime ↔ DateOnly/TimeOnly — automatic temporal conversions
  • Conversion operators — implicit/explicit operators detected automatically
  • String ↔ Numeric — int.Parse(), decimal.Parse(), bool.Parse(), .ToString()
  • Tuple compatibility — ValueTuple with same arity and compatible elements
  • Collection-to-collection — different element types with per-element mapping
  • Collection type conversion — same element, different container (List<T> → HashSet<T>)
  • Dictionary mapping — Dictionary<K, A> → Dictionary<K, B> with value mapping
  • Nested collections — List<List<A>> → List<List<B>>

Performance Optimizations

  • Constructor deduplication — properties satisfied by constructor parameters are not repeated in the object initializer
  • MapTo reuse — MapListTo and MapArrayTo delegate to an existing MapTo method when one exists with matching types
  • Direct array allocation — MapArrayTo writes directly into new T[count] when the source count is known, avoiding an intermediate List<T>.ToArray() copy
  • Incremental caching — all pipeline models implement IEquatable<T> for correct Roslyn incremental regeneration

Notes and Limits

  • mapping is convention-based unless attributes are used
  • generated code supports inherited readable source properties and writable destination properties
  • converters, profiles, DI registration, and runtime fluent configuration belong to the runtime packages, not to the generator
  • the generator is intended for strongly-defined compile-time maps

Diagnostics Quick Reference

  • PMAP001 mapper class must be partial
  • PMAP002 mapping method must be partial
  • PMAP003 unsupported method signature
  • PMAP004 no matching source property (informational)
  • PMAP005 invalid [MapFromPath]
  • PMAP006 invalid [MapFrom]
  • PMAP007 incompatible source/target member types
  • PMAP008 constructor parameter could not be mapped
  • PMAP009 enum-to-enum explicit cast (informational)
  • PMAP010 strict mode unmapped target property
  • PMAP011 invalid/missing [MapCustom] method
  • PMAP012 invalid/missing [MapCondition] method
  • PMAP013 projection contains potentially non-translatable expression for IQueryable providers

FAQ

  1. Does this library use AutoMapper internally? No. This package is a compile-time source generator and emits direct C# mapping code.

  2. Do I need runtime caches for generated mappings? Usually no. Generated mappers are normal classes with static compile-time mapping logic.

  3. Should I use ProjectTo or MapTo? Use ProjectTo for IQueryable providers when the expression is translatable. Use MapTo for in-memory objects.

Repository Contents

  • Pitasoft.ObjectMapping.Generator — Roslyn source generator package
  • Pitasoft.ObjectMapping.Generator.Tests — test suite (currently 329 tests in CI matrix)
  • Pitasoft.ObjectMapping.Generator.Benchmarks — benchmark suite (manual vs POG vs Mapperly vs AutoMapper vs TinyMapper vs ExpressMapper)
  • Pitasoft.ObjectMapping.Generator.Example — console demo with all features

Castellano

Pitasoft.ObjectMapping.Generator es un source generator de Roslyn para mapeo de objetos en tiempo de compilación.

Genera implementaciones de mappers a partir de clases parciales marcadas con [ObjectMapper] y está pensado para escenarios que buscan:

  • cero reflexión en runtime en rutas calientes
  • código compatible con AOT
  • generación en compilación de MapTo, MapInto, MapListTo y MapArrayTo
  • soporte para MapFrom, MapFromPath y MapIgnore
  • mapeo automático por herencia, interfaces y tipos enum
  • mapeo de propiedades colección (List<A> a List<B>, A[] a B[])

Instalación

dotnet add package Pitasoft.ObjectMapping
dotnet add package Pitasoft.ObjectMapping.Generator

Inicio Rápido (Listo Para NuGet)

Flujo mínimo para copiar y pegar en un proyecto nuevo:

  1. Instala paquetes:
dotnet add package Pitasoft.ObjectMapping
dotnet add package Pitasoft.ObjectMapping.Generator
  1. Define modelos de origen y destino:
public sealed class UserEntity
{
    public Guid Id { get; set; }
    public string Name { get; set; } = "";
    public string Email { get; set; } = "";
}

public sealed class UserDto
{
    public Guid Id { get; set; }
    public string Name { get; set; } = "";
    public string Email { get; set; } = "";
}
  1. Crea el mapper:
using Pitasoft.ObjectMapping;

[ObjectMapper]
public partial class UserMapper
{
    public partial UserDto MapTo(UserEntity source);
}
  1. Compila el proyecto. La implementación se genera en compilación.

  2. Usa el mapper:

var mapper = new UserMapper();
var dto = mapper.MapTo(new UserEntity
{
    Id = Guid.NewGuid(),
    Name = "Ada",
    Email = "ada@domain.test"
});

Recetas Prácticas (Detalladas)

Receta 1: DTO de lectura + actualización (MapTo + MapInto)

Usa MapTo para crear DTOs y MapInto para actualizar instancias existentes.

public sealed class ProductEntity
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public decimal Price { get; set; }
    public string InternalCode { get; set; } = "";
}

public sealed class ProductDto
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public decimal Price { get; set; }
}

[ObjectMapper]
public partial class ProductMapper
{
    public partial ProductDto MapTo(ProductEntity source);
    public partial void MapInto(ProductEntity source, ProductDto target);
}
var mapper = new ProductMapper();
var dto = mapper.MapTo(entity);
mapper.MapInto(entity, dto);
Receta 2: Consulta CQRS con proyección (ProjectTo)

Usa ProjectTo en consultas con proveedores IQueryable (por ejemplo EF Core).

using System.Linq.Expressions;
using Pitasoft.ObjectMapping;
using Pitasoft.ObjectMapping.Attributes;

public sealed class OrderEntity
{
    public int Id { get; set; }
    public CustomerEntity? Customer { get; set; }
    public decimal Total { get; set; }
    public decimal Discount { get; set; }
}

public sealed class CustomerEntity
{
    public string Name { get; set; } = "";
}

public sealed class OrderListItemDto
{
    public int Id { get; set; }
    [MapFromPath("Customer.Name")]
    public string? CustomerName { get; set; }
    [MapCondition("ShouldMapDiscount")]
    public decimal Discount { get; set; } = 0m;
    public decimal Total { get; set; }
}

[ObjectMapper]
public partial class OrderQueryMapper
{
    public partial Expression<Func<OrderEntity, OrderListItemDto>> ProjectTo();
    public bool ShouldMapDiscount(OrderEntity s) => s.Discount > 0;
}
var mapper = new OrderQueryMapper();
var query = dbContext.Orders.Select(mapper.ProjectTo());
var items = await query.ToListAsync(ct);

Recomendación:

  • Mantén la lógica de proyección simple y traducible por el proveedor.
  • Si una parte no es traducible, materializa (ToList) y aplica MapTo.
Receta 3: Capa API para escritura (MapInto + null-safe updates)

Muy útil en endpoints PATCH donde null no debe sobreescribir valores existentes.

public sealed class UpdateUserRequest
{
    public string? Name { get; set; }
    public string? Phone { get; set; }
}

public sealed class UserEntity
{
    public Guid Id { get; set; }
    public string Name { get; set; } = "";
    public string Phone { get; set; } = "";
}

[ObjectMapper(IgnoreNullValues = true)]
public partial class UserWriteMapper
{
    public partial void MapInto(UpdateUserRequest source, UserEntity target);
}
var mapper = new UserWriteMapper();
mapper.MapInto(request, entity);
Receta 4: Campo custom + mapeo condicional

Combina [MapCustom] y [MapCondition] para reglas claras de dominio.

using Pitasoft.ObjectMapping.Attributes;

public sealed class InvoiceEntity
{
    public string Number { get; set; } = "";
    public string CustomerName { get; set; } = "";
    public decimal Discount { get; set; }
}

public sealed class InvoiceDto
{
    [MapCustom("BuildDisplayName")]
    public string DisplayName { get; set; } = "";

    [MapCondition("ShouldMapDiscount")]
    public decimal Discount { get; set; } = 0m;
}

[ObjectMapper]
public partial class InvoiceMapper
{
    public partial InvoiceDto MapTo(InvoiceEntity source);

    public string BuildDisplayName(InvoiceEntity s) => $"{s.Number} - {s.CustomerName}";
    public bool ShouldMapDiscount(InvoiceEntity s) => s.Discount > 0;
}
Receta 5: Flattening + rutas explícitas en grafos anidados
public sealed class CustomerEntity
{
    public AddressEntity? Address { get; set; }
}

public sealed class AddressEntity
{
    public string City { get; set; } = "";
    public CountryEntity? Country { get; set; }
}

public sealed class CountryEntity
{
    public string Iso2 { get; set; } = "";
}

public sealed class CustomerDto
{
    // Flattening automático: AddressCity <- Address.City
    public string? AddressCity { get; set; }

    [MapFromPath("Address.Country.Iso2")]
    public string? CountryCode { get; set; }
}

[ObjectMapper]
public partial class CustomerMapper
{
    public partial CustomerDto MapTo(CustomerEntity source);
}

Checklist De Publicación En NuGet

Antes de publicar una nueva versión:

  1. Actualizar versión y changelog.
  2. Verificar que los ejemplos de README.md compilan con la API actual.
  3. Ejecutar dotnet test en todos los target frameworks.
  4. Revisar que la tabla de diagnósticos esté completa (actualmente PMAP001-PMAP013).
  5. Validar links de repositorio, licencia y metadatos de paquete.
  6. Confirmar que notas de proyección/EF reflejan comportamiento actual (PMAP013, inlining de MapCondition).

Uso básico

using Pitasoft.ObjectMapping;

[ObjectMapper]
public partial class CustomerMapper
{
    public partial CustomerDto MapTo(CustomerEntity source);
    public partial void MapInto(CustomerEntity source, CustomerDto target);
    public partial List<CustomerDto> MapListTo(IEnumerable<CustomerEntity> source);
    public partial CustomerDto[] MapArrayTo(IEnumerable<CustomerEntity> source);
}

El generador produce la implementación en tiempo de compilación.

Ejecutar Los Ejemplos Incluidos En Esta Solución

La solución ya trae proyectos ejecutables para validar comportamiento de forma inmediata:

# Ejemplo consola con escenarios de mapeo
dotnet run --project Pitasoft.ObjectMapping.Generator.Example/Pitasoft.ObjectMapping.Generator.Example.csproj

# Benchmarks (manual vs generado vs otras librerías)
dotnet run -c Release --project Pitasoft.ObjectMapping.Generator.Benchmarks/Pitasoft.ObjectMapping.Generator.Benchmarks.csproj

Ejemplo Detallado End-To-End

Este ejemplo combina mapeo por convención, flattening, MapFromPath, MapCustom, MapCondition, BeforeMap, AfterMap y proyección en un único mapper.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Pitasoft.ObjectMapping;
using Pitasoft.ObjectMapping.Attributes;

public sealed class CustomerEntity
{
    public int Id { get; set; }
    public string FirstName { get; set; } = "";
    public string LastName { get; set; } = "";
    public bool IsActive { get; set; }
    public DateTime CreatedAt { get; set; }
    public AddressEntity? Address { get; set; }
    public decimal Discount { get; set; }
}

public sealed class AddressEntity
{
    public string City { get; set; } = "";
    public CountryEntity? Country { get; set; }
}

public sealed class CountryEntity
{
    public string Code { get; set; } = "";
}

public sealed class CustomerDto
{
    [MapFrom("Id")]
    public int CustomerId { get; set; }

    // Mapeo por convención
    public bool IsActive { get; set; }

    // Flattening por nombre: AddressCity <- Address.City
    public string? AddressCity { get; set; }

    // Ruta explícita
    [MapFromPath("Address.Country.Code")]
    public string? CountryCode { get; set; }

    [MapCustom("ComputeFullName")]
    public string FullName { get; set; } = "";

    [MapCondition("ShouldMapDiscount")]
    public decimal Discount { get; set; } = -1m;

    [MapIgnore]
    public string? InternalComment { get; set; }
}

[ObjectMapper(IgnoreNullValues = true, CaseInsensitiveMatching = true)]
public partial class CustomerMapper
{
    public partial CustomerDto MapTo(CustomerEntity source);
    public partial void MapInto(CustomerEntity source, CustomerDto target);
    public partial List<CustomerDto> MapListTo(IEnumerable<CustomerEntity> source);
    public partial CustomerDto[] MapArrayTo(IEnumerable<CustomerEntity> source);
    public partial Expression<Func<CustomerEntity, CustomerDto>> ProjectTo();

    public string ComputeFullName(CustomerEntity source) => $"{source.FirstName} {source.LastName}";
    public bool ShouldMapDiscount(CustomerEntity source) => source.Discount > 0;

    public void BeforeMap(CustomerEntity source, CustomerDto target)
    {
        // Se ejecuta antes de las asignaciones generadas en MapTo/MapInto.
        target.InternalComment = "initialized";
    }

    public void AfterMap(CustomerEntity source, CustomerDto target)
    {
        // Se ejecuta después de las asignaciones generadas en MapTo/MapInto.
        if (!target.IsActive)
            target.InternalComment = "inactive";
    }
}

Uso:

var mapper = new CustomerMapper();

var entity = new CustomerEntity
{
    Id = 7,
    FirstName = "Ada",
    LastName = "Lovelace",
    IsActive = true,
    Discount = 10,
    Address = new AddressEntity
    {
        City = "London",
        Country = new CountryEntity { Code = "UK" }
    }
};

// Crear
var dto = mapper.MapTo(entity);

// Actualizar instancia existente
mapper.MapInto(entity, dto);

// Lotes
var list = mapper.MapListTo(new[] { entity });
var array = mapper.MapArrayTo(new[] { entity });

// Proyección IQueryable
var projected = new[] { entity }.AsQueryable().Select(mapper.ProjectTo()).ToList();

Registro En DI (Opcional)

Si instalas también Pitasoft.ObjectMapping.Generator.DependencyInjectionExtensions:

using System.Reflection;
using Pitasoft.ObjectMapping.Generator.DependencyInjectionExtensions;

var services = new ServiceCollection();

// Registra todos los mappers de uno o más ensamblados
services.AddObjectMappers(Assembly.GetExecutingAssembly());

// O registra un mapper concreto
services.AddObjectMapper<CustomerMapper>();

Notas De Proyección (ProjectTo)

  • ProjectTo devuelve Expression<Func<TSource, TTarget>>.
  • Está diseñado para proveedores IQueryable (por ejemplo EF Core).
  • Para mantener traducción 100% server-side, la lógica custom/condicional debe ser traducible por el proveedor.
  • MapCondition se inlinea en la proyección cuando es posible (por ejemplo s => s.Discount > 0).
  • Si MapCondition no se puede inlinear, o si la condición inlineada llama a helpers del mapper, el generador emite PMAP013 para avisar del riesgo de no traducción SQL.
  • Si el proveedor no traduce parte de la expresión, usa MapTo después de materializar (ToList()), o simplifica la lógica de proyección.

Mapeo por convención

public sealed class SimpleSource
{
    public int Id { get; set; }
    public string Value { get; set; } = string.Empty;
}

public sealed class SimpleTarget
{
    public int Id { get; set; }
    public string Value { get; set; } = string.Empty;
}

[ObjectMapper]
public partial class SimpleMapper
{
    public partial SimpleTarget MapTo(SimpleSource source);
    public partial void MapInto(SimpleSource source, SimpleTarget target);
}

MapFrom

using Pitasoft.ObjectMapping.Attributes;

public sealed class CustomerDto
{
    [MapFrom("Id")]
    public int CustomerId { get; set; }

    public string Name { get; set; } = string.Empty;
}

MapFromPath

using Pitasoft.ObjectMapping.Attributes;

public sealed class CustomerDto
{
    [MapFromPath("Address.City")]
    public string? City { get; set; }

    [MapFromPath("Address.Country.Code")]
    public string? CountryCode { get; set; }
}

El acceso generado a rutas anidadas es null-safe. Si un nodo intermedio es null, el código generado devuelve null para ese miembro destino.

MapIgnore

using Pitasoft.ObjectMapping.Attributes;

public sealed class CustomerDto
{
    public int CustomerId { get; set; }

    [MapIgnore]
    public string? ComputedField { get; set; }
}

Ignorar nulos en MapInto

[ObjectMapper(IgnoreNullValues = true)]
public partial class NullSafeMapper
{
    public partial void MapInto(CustomerEntity source, CustomerDto target);
}

Con IgnoreNullValues = true, los MapInto generados omiten valores null del origen en lugar de sobrescribir el destino.

Opciones de matching

[ObjectMapper(
    CaseInsensitiveMatching = true,
    SourcePrefixToIgnore = "Db",
    TargetPrefixToIgnore = "Customer")]
public partial class FlexibleMapper
{
    public partial CustomerDto MapTo(CustomerEntity source);
}

Estas opciones permiten ajustar el matching por convención en modelos heterogéneos.

Firmas parciales soportadas

  • TTarget MapTo(TSource source)
  • void MapInto(TSource source, TTarget target)
  • List<TTarget> MapListTo(IEnumerable<TSource> source)
  • IEnumerable<TTarget> MapListTo(IEnumerable<TSource> source)
  • ICollection<TTarget> MapListTo(IEnumerable<TSource> source)
  • IList<TTarget> MapListTo(IEnumerable<TSource> source)
  • IReadOnlyCollection<TTarget> MapListTo(IEnumerable<TSource> source)
  • IReadOnlyList<TTarget> MapListTo(IEnumerable<TSource> source)
  • TTarget[] MapArrayTo(IEnumerable<TSource> source)

Mapeo de enums

El generador soporta mapeo entre tipos enum distintos con los mismos valores subyacentes. Se emite un cast explícito automáticamente:

public enum StatusEntity { Active, Inactive }
public enum StatusDto { Active, Inactive }

public sealed class OrderEntity { public StatusEntity Status { get; set; } }
public sealed class OrderDto { public StatusDto Status { get; set; } }

[ObjectMapper]
public partial class OrderMapper
{
    public partial OrderDto MapTo(OrderEntity source);
}
// Generado: Status = (StatusDto)source.Status

Mapeo de propiedades colección

Cuando una propiedad origen es una colección de tipo A y el destino espera una colección de tipo B, el generador mapea los elementos individualmente usando LINQ:

public sealed class OrderEntity
{
    public List<OrderLineEntity> Lines { get; set; }
}

public sealed class OrderDto
{
    public List<OrderLineDto> Lines { get; set; }
}

[ObjectMapper]
public partial class OrderMapper
{
    public partial OrderDto MapTo(OrderEntity source);
}
// Generado: Lines = source.Lines.Select(x => new OrderLineDto { ... }).ToList()

Formas de colección soportadas: List<T>, IEnumerable<T>, ICollection<T>, IList<T>, IReadOnlyList<T>, IReadOnlyCollection<T> y T[].

Funcionalidades adicionales

El generador también soporta: auto-flattening (AddressCity → Address.City), [MapCustom], [MapCondition], AfterMap hooks, string ↔ enum, Nullable<T> → T (.GetValueOrDefault()), DateTime ↔ DateOnly/TimeOnly, operadores de conversión, StrictMapping, record struct, y tuplas.

Compatibilidad de tipos

El generador soporta los siguientes mapeos de tipos:

  • Exacto — mismo tipo en origen y destino
  • Ampliación nullable — T a T?
  • Reducción nullable — T? a T via .GetValueOrDefault()
  • Herencia — clase derivada a clase base
  • Implementación de interfaces — ej. List<T> a IEnumerable<T>
  • Enum a enum — tipos enum distintos mediante cast explícito
  • String ↔ Enum — Enum.Parse<T>() / .ToString()
  • DateTime ↔ DateOnly/TimeOnly — conversiones temporales automáticas
  • Operadores de conversión — operadores implicit/explicit detectados automáticamente
  • Tuplas — ValueTuple con misma aridad y elementos compatibles
  • Colección a colección — tipos de elemento distintos con mapeo por elemento
  • Diccionarios — Dictionary<K, A> → Dictionary<K, B> con mapeo de valores
  • Colecciones anidadas — List<List<A>> → List<List<B>>

Optimizaciones de rendimiento

  • Deduplicación de constructor — las propiedades satisfechas por parámetros de constructor no se repiten en el object initializer
  • Reutilización de MapTo — MapListTo y MapArrayTo delegan a un MapTo existente cuando hay uno con tipos coincidentes
  • Asignación directa de arrays — MapArrayTo escribe directamente en new T[count] cuando se conoce el tamaño de la fuente, evitando la copia intermedia de List<T>.ToArray()
  • Caché incremental — todos los modelos del pipeline implementan IEquatable<T> para regeneración incremental correcta en Roslyn

Notas y límites

  • el mapeo es por convención salvo que se usen atributos
  • el código generado soporta propiedades heredadas legibles en origen y escribibles en destino
  • los converters, perfiles, DI y configuración fluida en runtime pertenecen a los paquetes runtime, no al generador
  • el generador está pensado para mapas definidos en compilación y contratos estáticos

Referencia Rápida De Diagnósticos

  • PMAP001 la clase mapper debe ser partial
  • PMAP002 el método de mapeo debe ser partial
  • PMAP003 firma de método no soportada
  • PMAP004 no hay propiedad origen compatible (informativo)
  • PMAP005 [MapFromPath] inválido
  • PMAP006 [MapFrom] inválido
  • PMAP007 tipos incompatibles entre origen y destino
  • PMAP008 parámetro de constructor no resoluble
  • PMAP009 cast explícito enum-a-enum (informativo)
  • PMAP010 propiedad destino sin mapear en modo estricto
  • PMAP011 método [MapCustom] inválido o no encontrado
  • PMAP012 método [MapCondition] inválido o no encontrado
  • PMAP013 la proyección contiene expresiones potencialmente no traducibles por proveedores IQueryable

FAQ

  1. Esta librería usa AutoMapper internamente? No. Este paquete es un source generator en compilación y emite código C# de mapeo directo.

  2. Hace falta caché en runtime para los mapeos generados? Normalmente no. Los mappers generados son clases normales con lógica de mapeo estática en compilación.

  3. Cuándo usar ProjectTo y cuándo MapTo? Usa ProjectTo con proveedores IQueryable cuando la expresión sea traducible. Usa MapTo para objetos en memoria.

Contenido del repositorio

  • Pitasoft.ObjectMapping.Generator paquete principal del source generator
  • Pitasoft.ObjectMapping.Generator.Tests suite de tests (actualmente 329 pruebas en la matriz CI)
  • Pitasoft.ObjectMapping.Generator.Benchmarks suite de benchmarks (manual vs generado vs AutoMapper)
  • Pitasoft.ObjectMapping.Generator.Example proyecto demo ejecutable con todas las funcionalidades
There are no supported framework assets in this package.

Learn more about Target Frameworks and .NET Standard.

  • .NETStandard 2.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.1 183 4/18/2026