LowCodeHub.ObjectMapper 0.0.13

There is a newer version of this package available.
See the version list below for details.
dotnet add package LowCodeHub.ObjectMapper --version 0.0.13
                    
NuGet\Install-Package LowCodeHub.ObjectMapper -Version 0.0.13
                    
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="LowCodeHub.ObjectMapper" Version="0.0.13" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="LowCodeHub.ObjectMapper" Version="0.0.13" />
                    
Directory.Packages.props
<PackageReference Include="LowCodeHub.ObjectMapper" />
                    
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 LowCodeHub.ObjectMapper --version 0.0.13
                    
#r "nuget: LowCodeHub.ObjectMapper, 0.0.13"
                    
#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 LowCodeHub.ObjectMapper@0.0.13
                    
#: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=LowCodeHub.ObjectMapper&version=0.0.13
                    
Install as a Cake Addin
#tool nuget:?package=LowCodeHub.ObjectMapper&version=0.0.13
                    
Install as a Cake Tool

LowCodeHub.ObjectMapper

A zero-overhead object mapper for .NET powered by C# interceptors and incremental source generation. Every mapping call is replaced at compile time with plain property assignments — no reflection, no expression trees, AOT- and trimming-safe. Mistakes show up as build diagnostics, not runtime exceptions.

NuGet License: MIT

Quick start

dotnet add package LowCodeHub.ObjectMapper
using LowCodeHub.ObjectMapper;

UserDto dto = ObjectMapper.Map<User, UserDto>(user);                    // new object
List<UserDto> list = ObjectMapper.MapList<User, UserDto>(users);        // sequences
ObjectMapper.Map<UpdateUser, User>(request, existingUser);              // into an existing object
User copy = ObjectMapper.Clone(user);                                   // deep clone

Nothing else to configure: the package's buildTransitive props adds LowCodeHub.ObjectMapper.Generated to InterceptorsNamespaces for you.

Map returns a MappingResult<TSource, TDest> that implicitly converts to TDest. Assign it to a typed variable (as above) or read .Destination — var x = ObjectMapper.Map<A, B>(a) gives you the MappingResult, not B.

Customize a single call with the fluent chain:

UserDto dto = ObjectMapper.Map<User, UserDto>(user)
    .Adapt(s => s.BirthYear, d => d.Year)             // differently named property
    .Ignore(d => d.PasswordHash)                     // leave unmapped
    .Transform(d => d.FullName, s => $"{s.First} {s.Last}");

Contents


Matching rules

  • Properties are matched by name, case-insensitively: public getter on the source, public set or public init on the destination (a private init does not count).
  • Unmatched destination properties keep their initializer value and are listed in the OMAP003 build summary.
  • Destination names of the form {Nested}{Property} are flattened from the source (AddressCity ← source.Address?.City).
  • Destinations without a parameterless constructor (positional records) are created through the largest public constructor, parameters matched by name.
  • Source and destination types (and every type named in generated code) must be public or internal, including containing types — otherwise OMAP010.

Fluent API

All methods return the MappingResult, so they chain in any order. Every lambda selector must be a simple member access on the lambda parameter (d => d.Name) — anything else is OMAP004.

Method Effect
.Adapt(s => s.A, d => d.B) d.B = s.A
.Ignore(d => d.B) Leave B unmapped (see below)
.Set(d => d.B, value) d.B = value
.Transform(d => d.B, s => expr) d.B = expr(s)
.Condition(d => d.B, s => predicate) When false: default (new object) / untouched (existing object)
.Condition(d => d.B, s => predicate, fallback) When false: d.B = fallback
.NullSubstitute(d => d.B, fallback) When d.B is null after mapping: d.B = fallback
.AdaptEach(s => s.Items, d => d.Items, (se, de) => ...) Runs an action on each paired element after mapping
.AfterMap((s, d) => ...) Runs last with source and destination

Ignore chained directly on Map/Clone removes the member from the generated mapping: a new object keeps its initializer value, an existing object keeps its current value. If you call Ignore later on a stored MappingResult, it resets the member to default instead.

Init-only destination members in fluent calls are applied with with { ... } for records, or by re-creating the object (classes with a parameterless constructor). Anything else is OMAP007. Members without an accessible setter are OMAP015.


Attributes

public class UserDto
{
    [MapFrom("FirstName")]      public string GivenName { get; set; } = "";
    [MapFrom("Address.City")]   public string HomeCity { get; set; } = "";   // dotted path, null-safe
    [MapIgnore]                 public string InternalNote { get; set; } = "";
}

[MapFrom] / [MapIgnore] apply to every mapping into that type, including nested ones.


Nested objects, recursion and cycles

Nested objects with matching property names are mapped through a generated helper method per type pair. A null nested source gives a null destination (or default for a struct destination).

Recursive types map at any depth — trees, linked lists, Node { List<Node> Children }:

NodeDto dto = ObjectMapper.Map<Node, NodeDto>(root);   // whole tree

Cyclic object graphs (parent back-pointers, EF navigation pairs) are tracked per call:

  • Destinations built with a parameterless constructor and settable properties: cycles are preserved (dto.Children[0].Parent is dto), shared references stay shared.
  • Destinations built through a constructor / init / required members cannot reference themselves before they exist. Trees still map, but a cycle throws InvalidOperationException ("circular reference detected…"); the build reports OMAP009 (info) for such type pairs.

Collections and dictionaries

Collection properties are mapped element by element (elements can need any conversion: nested objects, enums, numerics, …). Top-level sequences:

List<Dto>     list  = ObjectMapper.MapList<Entity, Dto>(entities);
Dto[]         array = ObjectMapper.MapArray<Entity, Dto>(entities);
HashSet<Dto>  set   = ObjectMapper.MapSet<Entity, Dto>(entities);
ImmutableArray<Dto> imm = ObjectMapper.Map<List<Entity>, ImmutableArray<Dto>>(entities);

Supported destination types:

Destination Built with
T[], IReadOnlyList<T>, IReadOnlyCollection<T> array
List<T>, IList<T>, ICollection<T>, IEnumerable<T> List<T>
HashSet<T>, ISet<T>, IReadOnlySet<T> HashSet<T> (same element type keeps the source HashSet comparer)
ImmutableArray/List/HashSet/SortedSet<T>, IImmutableList<T>, IImmutableSet<T>, FrozenSet<T> CreateRange / ToFrozenSet
Any concrete type with a public (IEnumerable<T>) or (IList<T>) constructor — ObservableCollection<T>, Collection<T>, ReadOnlyCollection<T>, Queue<T>, SortedSet<T>, … that constructor
Any concrete ICollection<T> with a parameterless constructor new T() + Add

Stack<T> (order would be reversed) and other types are not supported: the property is skipped with OMAP012 (a top-level call fails with OMAP011).

Dictionaries need identical key types; values may need conversion. Destinations: Dictionary, IDictionary, IReadOnlyDictionary, SortedDictionary, SortedList, ConcurrentDictionary, ImmutableDictionary, ImmutableSortedDictionary, FrozenDictionary. The source key comparer is preserved when the source is a Dictionary/ConcurrentDictionary/FrozenDictionary/ImmutableDictionary (or a sorted dictionary for sorted destinations).

A property whose source and destination types are identical (e.g. List<string> → List<string>) is copied by reference in Map; use Clone for independent copies.


Map into an existing object

ObjectMapper.Map<UpdateUserRequest, User>(request, user)
    .Ignore(d => d.Email)                    // keeps user.Email
    .Condition(d => d.Name, s => s.Name != "");   // keeps user.Name unless the predicate holds
  • Matched settable properties are overwritten; unmatched properties are untouched.
  • A null nested object / collection / dictionary on the source, an unparsable string, or an unknown enum name leaves the existing value in place.
  • init-only members cannot be assigned after construction: they are skipped with OMAP013.
  • Mapping into an existing collection is not supported (OMAP011); assign the result of Map instead.

Clone

ObjectMapper.Clone(x) deep-copies: nested objects, collections and dictionaries are rebuilt, cycles are preserved (see above). Members typed as an abstract class or interface cannot be rebuilt and are copied by reference. Clone<List<T>> clones each element.


Null handling

Call Source is null
Map<User, UserDto>(null) ArgumentNullException("source") with a hint
Map<User?, UserDto?>(null) returns null
Map<User, UserDto>(null, existing) ArgumentNullException("source")
Map<User?, UserDto>(null, existing) returns existing unchanged
Map(source, null) ArgumentNullException("destination")
MapList/MapArray/MapSet(null) ArgumentNullException("source")

null elements inside a collection map to null elements. null nested objects map to null.


Type conversions

Source → Destination Behaviour
T? → T GetValueOrDefault()
T → T? implicit
numeric → numeric (incl. nullable) cast; narrowing casts are checked and throw OverflowException
enum → enum by member name (aliases handled; [Flags] combinations mapped bit by bit); unknown values → default; no common names → checked cast of the underlying value
string → enum Enum.TryParse(ignoreCase: true); failure → default
enum → string ToString()
string → Guid, DateTime, DateTimeOffset, DateOnly, TimeOnly, TimeSpan, Uri, Version TryParse with InvariantCulture; failure or null → default / null
those types → string ToString() (date/time types with InvariantCulture)
DateTime ↔ DateTimeOffset new DateTimeOffset(value) / .DateTime

Records, init-only and required members

  • Positional records: created through the constructor; remaining settable members via object initializer.
  • init members: set in the object initializer on Map/Clone; see the fluent and existing-object rules above.
  • required members without a source match are set to default! (OMAP006) so the code compiles; give them a value with .Set(...).

Diagnostics

Code Severity Meaning
<a id="omap001"></a>OMAP001 Error Open generic type arguments (Map<T, D> inside a generic method) — use concrete types
<a id="omap002"></a>OMAP002 Warning No matching properties between source and destination
<a id="omap003"></a>OMAP003 Info Mapping summary listing unmapped destination properties (has a code fix, see below)
<a id="omap004"></a>OMAP004 Error Selector lambda is not x => x.Member on the lambda parameter
<a id="omap005"></a>OMAP005 Warning Destination property with a matching name has no public setter; skipped
<a id="omap006"></a>OMAP006 Warning required property has no source match; set to default
<a id="omap007"></a>OMAP007 Error Fluent call targets an init-only property on a non-record class without a parameterless constructor
<a id="omap008"></a>OMAP008 Error Call site cannot be intercepted (e.g. the compiler does not support interceptors)
<a id="omap009"></a>OMAP009 Info Recursive type pair whose destination is built via constructor/init/required: cyclic graphs throw at runtime
<a id="omap010"></a>OMAP010 Error A type is private/protected/file-local/anonymous and cannot be named by generated code
<a id="omap011"></a>OMAP011 Error Destination cannot be created (abstract, interface, no public constructor, not an object type, unsupported top-level collection)
<a id="omap012"></a>OMAP012 Warning Destination collection type of a property is not supported; property skipped
<a id="omap013"></a>OMAP013 Warning Map(source, existing) cannot assign an init-only property; it keeps its value
<a id="omap014"></a>OMAP014 Error Internal generator failure for one call site (other call sites still work) — please report it
<a id="omap015"></a>OMAP015 Error Fluent call targets a member without an accessible setter

If InterceptorsNamespaces does not include LowCodeHub.ObjectMapper.Generated (only possible when you wire the generator by hand instead of using the package), the compiler fails with CS9137 at each generated interceptor.

Every Map call that is not intercepted throws InvalidOperationException at runtime, so treat any of the errors above as blocking.

Code fix: ignore unmapped properties

For OMAP003 on Map/Clone calls the IDE lightbulb appends .Ignore(d => d.Prop) for each unmapped property, which silences the summary and documents intent. It is not offered for MapList/MapArray/MapSet (use [MapIgnore] on the element type there). Suppress the summary project-wide with <NoWarn>$(NoWarn);OMAP003</NoWarn>.


How it works

  1. The incremental generator finds every ObjectMapper.Map/MapList/MapArray/MapSet/Clone call and every fluent MappingResult call.
  2. For each call site it matches members, then emits one file with an [InterceptsLocation] method that replaces that exact call, plus one private helper method per nested (source, destination) type pair.
  3. At runtime the interceptor runs plain assignments; the stub method bodies in the library (which throw) are never reached.

The pipeline caches per call site, so editing unrelated code does not regenerate existing interceptors. One failing call site reports OMAP014 without affecting the others.

Testing the packed package

test/LowCodeHub.ObjectMapper.PackageConsumer restores the package from artifacts/nupkg at the version in this project's csproj:

dotnet pack src/LowCodeHub.ObjectMapper/LowCodeHub.ObjectMapper.csproj -c Release -o artifacts/nupkg
dotnet run --project test/LowCodeHub.ObjectMapper.PackageConsumer   # exit code 0 = OK

Requirements

  • Projects targeting .NET 10 (the runtime library is net10.0).
  • A C# compiler with interceptor support — any .NET 10 SDK. The generator is built against Roslyn 4.11 so it loads in every such compiler.
  • AOT / trimming: no reflection; mapped types are referenced statically by the generated code.

License

MIT © Ahmed Abuelnour

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net10.0

    • No dependencies.

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
0.1.0 174 11/15/2026
0.0.13 193 10/22/2026
0.0.12 1,007 7/10/2026
0.0.11 143 7/9/2026
0.0.10 189 6/21/2026
0.0.9 180 5/18/2026
0.0.8 139 5/12/2026
0.0.7 182 4/23/2026
0.0.6 140 4/19/2026
0.0.5 123 4/19/2026
0.0.4 156 4/16/2026
0.0.3 127 4/16/2026
0.0.2 123 4/16/2026
0.0.1 130 4/16/2026