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
<PackageReference Include="Pitasoft.ObjectMapping.Generator" Version="1.0.1"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference>
<PackageVersion Include="Pitasoft.ObjectMapping.Generator" Version="1.0.1" />
<PackageReference Include="Pitasoft.ObjectMapping.Generator"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference>
paket add Pitasoft.ObjectMapping.Generator --version 1.0.1
#r "nuget: Pitasoft.ObjectMapping.Generator, 1.0.1"
#:package Pitasoft.ObjectMapping.Generator@1.0.1
#addin nuget:?package=Pitasoft.ObjectMapping.Generator&version=1.0.1
#tool nuget:?package=Pitasoft.ObjectMapping.Generator&version=1.0.1
Pitasoft.ObjectMapping.Generator
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, andMapArrayTo - support for
MapFrom,MapFromPath, andMapIgnore - automatic mapping through inheritance, interfaces, and enum types
- collection property mapping (
List<A>toList<B>,A[]toB[])
Installation
dotnet add package Pitasoft.ObjectMapping
dotnet add package Pitasoft.ObjectMapping.Generator
NuGet-Ready Quick Start
Copy/paste this flow in a clean project:
- Install packages:
dotnet add package Pitasoft.ObjectMapping
dotnet add package Pitasoft.ObjectMapping.Generator
- 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; } = "";
}
- Add a mapper:
using Pitasoft.ObjectMapping;
[ObjectMapper]
public partial class UserMapper
{
public partial UserDto MapTo(UserEntity source);
}
Build the project. The implementation is generated at compile time.
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:
- Version and changelog are updated.
README.mdexamples compile against current API.dotnet testpasses for all target frameworks.- Diagnostics section includes all active IDs (currently
PMAP001-PMAP013). - Repository links and package metadata are valid.
- 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)
ProjectToreturnsExpression<Func<TSource, TTarget>>.- This is intended for
IQueryableproviders (for example EF Core). - For full server-side translation, custom/conditional logic must be provider-translatable.
MapConditionis inlined into the projection when possible (for examples => s.Discount > 0).- If
MapConditioncannot be inlined, or if the inlined condition calls a helper method on the mapper, the generator emitsPMAP013so you can review SQL translatability risk. - If your provider cannot translate a part of the expression, use
MapToafter 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→DateOnlyviaDateOnly.FromDateTime()DateTime→TimeOnlyviaTimeOnly.FromDateTime()DateOnly→DateTimevia.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 —
TtoT? - Nullable unwrapping —
T?toTvia.GetValueOrDefault() - Inheritance — derived class to base class
- Interface implementation — e.g.
List<T>toIEnumerable<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 —
ValueTuplewith 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 —
MapListToandMapArrayTodelegate to an existingMapTomethod when one exists with matching types - Direct array allocation —
MapArrayTowrites directly intonew T[count]when the source count is known, avoiding an intermediateList<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
PMAP001mapper class must bepartialPMAP002mapping method must bepartialPMAP003unsupported method signaturePMAP004no matching source property (informational)PMAP005invalid[MapFromPath]PMAP006invalid[MapFrom]PMAP007incompatible source/target member typesPMAP008constructor parameter could not be mappedPMAP009enum-to-enum explicit cast (informational)PMAP010strict mode unmapped target propertyPMAP011invalid/missing[MapCustom]methodPMAP012invalid/missing[MapCondition]methodPMAP013projection contains potentially non-translatable expression forIQueryableproviders
FAQ
Does this library use AutoMapper internally? No. This package is a compile-time source generator and emits direct C# mapping code.
Do I need runtime caches for generated mappings? Usually no. Generated mappers are normal classes with static compile-time mapping logic.
Should I use
ProjectToorMapTo? UseProjectToforIQueryableproviders when the expression is translatable. UseMapTofor in-memory objects.
Repository Contents
Pitasoft.ObjectMapping.Generator— Roslyn source generator packagePitasoft.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,MapListToyMapArrayTo - soporte para
MapFrom,MapFromPathyMapIgnore - mapeo automático por herencia, interfaces y tipos enum
- mapeo de propiedades colección (
List<A>aList<B>,A[]aB[])
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:
- Instala paquetes:
dotnet add package Pitasoft.ObjectMapping
dotnet add package Pitasoft.ObjectMapping.Generator
- 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; } = "";
}
- Crea el mapper:
using Pitasoft.ObjectMapping;
[ObjectMapper]
public partial class UserMapper
{
public partial UserDto MapTo(UserEntity source);
}
Compila el proyecto. La implementación se genera en compilación.
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 aplicaMapTo.
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:
- Actualizar versión y changelog.
- Verificar que los ejemplos de
README.mdcompilan con la API actual. - Ejecutar
dotnet testen todos los target frameworks. - Revisar que la tabla de diagnósticos esté completa (actualmente
PMAP001-PMAP013). - Validar links de repositorio, licencia y metadatos de paquete.
- Confirmar que notas de proyección/EF reflejan comportamiento actual (
PMAP013, inlining deMapCondition).
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)
ProjectTodevuelveExpression<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.
MapConditionse inlinea en la proyección cuando es posible (por ejemplos => s.Discount > 0).- Si
MapConditionno se puede inlinear, o si la condición inlineada llama a helpers del mapper, el generador emitePMAP013para avisar del riesgo de no traducción SQL. - Si el proveedor no traduce parte de la expresión, usa
MapTodespué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 —
TaT? - Reducción nullable —
T?aTvia.GetValueOrDefault() - Herencia — clase derivada a clase base
- Implementación de interfaces — ej.
List<T>aIEnumerable<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 —
ValueTuplecon 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 —
MapListToyMapArrayTodelegan a unMapToexistente cuando hay uno con tipos coincidentes - Asignación directa de arrays —
MapArrayToescribe directamente ennew T[count]cuando se conoce el tamaño de la fuente, evitando la copia intermedia deList<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
PMAP001la clase mapper debe serpartialPMAP002el método de mapeo debe serpartialPMAP003firma de método no soportadaPMAP004no hay propiedad origen compatible (informativo)PMAP005[MapFromPath]inválidoPMAP006[MapFrom]inválidoPMAP007tipos incompatibles entre origen y destinoPMAP008parámetro de constructor no resolublePMAP009cast explícito enum-a-enum (informativo)PMAP010propiedad destino sin mapear en modo estrictoPMAP011método[MapCustom]inválido o no encontradoPMAP012método[MapCondition]inválido o no encontradoPMAP013la proyección contiene expresiones potencialmente no traducibles por proveedoresIQueryable
FAQ
Esta librería usa AutoMapper internamente? No. Este paquete es un source generator en compilación y emite código C# de mapeo directo.
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.
Cuándo usar
ProjectToy cuándoMapTo? UsaProjectTocon proveedoresIQueryablecuando la expresión sea traducible. UsaMapTopara objetos en memoria.
Contenido del repositorio
Pitasoft.ObjectMapping.Generatorpaquete principal del source generatorPitasoft.ObjectMapping.Generator.Testssuite de tests (actualmente 329 pruebas en la matriz CI)Pitasoft.ObjectMapping.Generator.Benchmarkssuite de benchmarks (manual vs generado vs AutoMapper)Pitasoft.ObjectMapping.Generator.Exampleproyecto demo ejecutable con todas las funcionalidades
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 |