Skip to content

API Reference

Arnel Robles edited this page Sep 28, 2026 · 1 revision

API Reference

Core Extensions (using Mapsicle)

MapTo<T>(this object source)

Maps a source object to a new instance of type T.

Parameters:

  • source - The source object to map from

Returns:

  • T? - New instance of T with mapped properties, or default(T) if source is null or max depth exceeded

Example:

var dto = user.MapTo<UserDto>();

MapTo<T>(this IEnumerable source)

Maps a collection to a List.

Parameters:

  • source - The source collection

Returns:

  • List<T> - New list with mapped items (empty if source is null)

Optimization: Pre-allocates capacity if source implements ICollection

Example:

List<UserDto> dtos = users.MapTo<UserDto>();

Map<TDest>(this object source, TDest destination)

Updates an existing destination object from source.

Parameters:

  • source - The source object
  • destination - The destination object to update

Returns:

  • TDest - The updated destination (same instance)

Example:

source.Map(existingDto);  // Updates existingDto in-place

ToDictionary(this object source)

Converts an object to a dictionary of property name/value pairs.

Returns:

  • Dictionary<string, object?> - Case-insensitive dictionary

Example:

var dict = user.ToDictionary();

MapTo<T>(this IDictionary<string, object?> source) where T : new()

Maps a dictionary to an object.

Constraints:

  • T must have a parameterless constructor

Example:

var user = dict.MapTo<User>();

Static Mapper Configuration

Mapper.MaxDepth

  • Type: int
  • Default: 32
  • Description: Maximum recursion depth before returning default value (circular reference protection)
Mapper.MaxDepth = 64;

Mapper.UseLruCache

  • Type: bool
  • Default: false
  • Description: Enables memory-bounded LRU cache. Clears all caches when changed.
Mapper.UseLruCache = true;

Mapper.MaxCacheSize

  • Type: int
  • Default: 1000
  • Description: Maximum cache entries when UseLruCache is enabled
Mapper.MaxCacheSize = 2000;

Mapper.Logger

  • Type: Action<string>?
  • Default: null
  • Description: Logger for diagnostic messages (depth warnings, etc)
Mapper.Logger = msg => _logger.LogDebug(msg);

Mapper.ClearCache()

Clears all cached mapping delegates.

Mapper.ClearCache();

Mapper.CacheInfo()

  • Returns: MapperCacheInfo - Current cache statistics
var stats = Mapper.CacheInfo();
Console.WriteLine($"Total: {stats.Total}, Hit Ratio: {stats.HitRatio:P1}");

Mapper.AssertMappingValid<TSource, TDest>()

Validates mapping configuration. Throws InvalidOperationException if unmapped properties exist.

Mapper.AssertMappingValid<User, UserDto>();

Mapper.GetUnmappedProperties<TSource, TDest>()

  • Returns: List<string> - Names of destination properties that cannot be mapped
var unmapped = Mapper.GetUnmappedProperties<User, UserDto>();

MapperFactory

MapperFactory.Create(MapperOptions? options = null)

Creates an isolated mapper instance with independent cache and depth tracking.

Parameters:

  • options - Optional configuration (MaxDepth, Logger, MaxCacheSize). An instance's caches are always LRU and bounded by MaxCacheSize; Mapper.UseLruCache applies to the static mapper only.

Returns:

  • IDisposable mapper instance

Example:

using var mapper = MapperFactory.Create(new MapperOptions
{
    MaxDepth = 16,
    MaxCacheSize = 100,
    Logger = Console.WriteLine
});
var dto = mapper.MapTo<UserDto>(user);

Fluent API (using Mapsicle.Fluent)

MapperConfiguration

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<User, UserDto>()
        .ForMember(d => d.FullName, opt => opt.MapFrom(s => s.FirstName + " " + s.LastName))
        .ForMember(d => d.Password, opt => opt.Ignore())
        .ForMember(d => d.IsActive, opt => opt.Condition(s => s.Status == "Active"))
        .BeforeMap((src, dest) => Console.WriteLine("Mapping started"))
        .AfterMap((src, dest) => dest.MappedAt = DateTime.UtcNow)
        .Include<PowerUser, PowerUserDto>()
        .ConstructUsing(src => new UserDto(src.Id))
        .ReverseMap();

    cfg.CreateConverter<Money, decimal>(m => m.Amount);
});

config.AssertConfigurationIsValid();
var mapper = config.CreateMapper();

Configuration Methods

  • ForMember<TMember>() - Configure individual member mapping

    • opt.MapFrom(expr) - Map from custom expression
    • opt.Ignore() - Don't map this member
    • opt.Condition(pred) - Conditional mapping
    • opt.ResolveUsing(func) - Custom resolver function
  • BeforeMap(action) - Execute action before mapping

  • AfterMap(action) - Execute action after mapping

  • Include<TDerived, TDest>() - Polymorphic mapping support

  • ConstructUsing(factory) - Custom object construction

  • ReverseMap() - Create reverse mapping

  • CreateConverter<TSource, TDest>(converter) - Global type converter


EntityFramework Extensions (using Mapsicle.EntityFramework)

ProjectTo<TSource, TDest>(this IQueryable<TSource> query, MapperConfiguration? config = null)

Translates mapping to SQL expression (executed in database).

Parameters:

  • query - Source EF Core queryable
  • config - Optional mapper configuration for custom mappings

Returns:

  • IQueryable<TDest> - Queryable projection

Example:

var dtos = await context.Users
    .Where(u => u.IsActive)
    .ProjectTo<User, UserDto>(config)
    .ToListAsync();

Validation Extensions (using Mapsicle.Validation)

MapAndValidate<TDest, TValidator>(this IMapper mapper, object? source)

Maps source to destination and validates using the specified validator type.

Type Parameters:

  • TDest - Destination type
  • TValidator - FluentValidation validator type (must have parameterless constructor)

Returns:

  • MapperValidationResult<TDest> - Contains IsValid, Value, Errors, ErrorsByProperty

Example:

var result = mapper.MapAndValidate<User, UserDto, UserDtoValidator>(user);
if (result.IsValid) return result.Value;

MapAndValidate<TDest>(this IMapper mapper, object? source, IValidator<TDest> validator)

Maps source to destination and validates using a provided validator instance.

Example:

var validator = new UserDtoValidator();
var result = mapper.MapAndValidate<UserDto>(user, validator);

Validate<T, TValidator>(this T value)

Validates an existing object using the specified validator type.

Example:

var result = dto.Validate<UserDto, UserDtoValidator>();

NamingConventions Extensions (using Mapsicle.NamingConventions)

MapWithConvention<TSource, TDest>(this TSource source, NamingConvention sourceConvention, NamingConvention destConvention)

Maps source to destination with naming convention transformation.

Parameters:

  • sourceConvention - The naming convention of source properties
  • destConvention - The naming convention of destination properties

Returns:

  • TDest? - New instance with convention-matched properties

Example:

var dto = apiResponse.MapWithConvention<ApiResponse, UserDto>(
    NamingConvention.SnakeCase,
    NamingConvention.PascalCase);

ConvertName(this string name, NamingConvention from, NamingConvention to)

Converts a property name from one convention to another.

Example:

var snakeName = "UserName".ConvertName(NamingConvention.PascalCase, NamingConvention.SnakeCase);
// Result: "user_name"

NamingConvention.NamesMatch(string sourceName, NamingConvention sourceConvention, string destName, NamingConvention destConvention)

Checks if two names match when their conventions are applied.

Example:

bool match = NamingConvention.NamesMatch("user_id", NamingConvention.SnakeCase, "UserId", NamingConvention.PascalCase);
// Result: true

Serilog Extensions (using Mapsicle.Serilog)

SerilogExtensions.UseSerilog(ILogger logger, Action<LoggingOptions>? configure = null)

Sets the logger every MapWithLogging call writes to, and routes Mapper.Logger to it.

SerilogExtensions.UseSerilog(Log.Logger, o => o.SlowMappingThreshold = TimeSpan.FromMilliseconds(50));

MapWithLogging<TDest>(this object? source)

Maps with timing, logged at Information. A failure is logged at Error and rethrown. Returns TDest?.

var dto = user.MapWithLogging<UserDto>();

MapCollectionWithLogging<TDest>(this IEnumerable? source)

Maps a collection and logs the count and total time. Returns List<TDest>, empty for a null source.

var dtos = users.MapCollectionWithLogging<UserDto>();

LoggingOptions.SlowMappingThreshold

  • Type: TimeSpan?
  • Default: null (no slow-mapping warnings)

Set through the configure action of UseSerilog.


SerilogExtensions.BeginMappingScope(string operationName)

Returns a MappingLoggingScope. Call RecordMapping() and RecordError() on it; disposing logs the totals and elapsed time.


Dapper Extensions (using Mapsicle.Dapper)

QueryAndMap<TSource, TDest>(this IDbConnection connection, string sql, ...)

Executes a SQL query and maps results to destination type.

Overloads:

  • QueryAndMap<TSource, TDest>(sql, param?, transaction?, commandTimeout?) - Auto-mapping
  • QueryAndMap<TSource, TDest>(sql, MapperConfiguration, param?, ...) - With configuration
  • QueryAndMap<TSource, TDest>(sql, IMapper, param?, ...) - With mapper instance

Returns:

  • IEnumerable<TDest> - Mapped results

Example:

var users = connection.QueryAndMap<User, UserDto>("SELECT * FROM Users").ToList();

QueryAndMapAsync<TSource, TDest>(this IDbConnection connection, string sql, ...)

Async version of QueryAndMap.

Example:

var users = await connection.QueryAndMapAsync<User, UserDto>("SELECT * FROM Users");

QuerySingleAndMap<TSource, TDest>(this IDbConnection connection, string sql, ...)

Executes a query expecting a single result and maps it.

Returns:

  • TDest? - Mapped result or null

Example:

var user = connection.QuerySingleAndMap<User, UserDto>(
    "SELECT * FROM Users WHERE Id = @Id", param: new { Id = 1 });

QueryFirstAndMap<TSource, TDest>(this IDbConnection connection, string sql, ...)

Executes a query and maps the first result.

Returns:

  • TDest? - First mapped result or null

Example:

var user = connection.QueryFirstAndMap<User, UserDto>("SELECT * FROM Users ORDER BY CreatedAt DESC");

MapTo<TSource, TDest>(this IEnumerable<TSource>? source, IMapper mapper)

Maps an existing collection using a provided mapper.

Returns:

  • List<TDest> - Mapped results

Example:

var users = connection.Query<User>("SELECT * FROM Users");
var dtos = users.MapTo<User, UserDto>(mapper);

Clone this wiki locally