-
Notifications
You must be signed in to change notification settings - Fork 1
API Reference
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, ordefault(T)if source is null or max depth exceeded
Example:
var dto = user.MapTo<UserDto>();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>();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-placeConverts an object to a dictionary of property name/value pairs.
Returns:
-
Dictionary<string, object?>- Case-insensitive dictionary
Example:
var dict = user.ToDictionary();Maps a dictionary to an object.
Constraints:
- T must have a parameterless constructor
Example:
var user = dict.MapTo<User>();-
Type:
int -
Default:
32 - Description: Maximum recursion depth before returning default value (circular reference protection)
Mapper.MaxDepth = 64;-
Type:
bool -
Default:
false - Description: Enables memory-bounded LRU cache. Clears all caches when changed.
Mapper.UseLruCache = true;-
Type:
int -
Default:
1000 - Description: Maximum cache entries when UseLruCache is enabled
Mapper.MaxCacheSize = 2000;-
Type:
Action<string>? -
Default:
null - Description: Logger for diagnostic messages (depth warnings, etc)
Mapper.Logger = msg => _logger.LogDebug(msg);Clears all cached mapping delegates.
Mapper.ClearCache();-
Returns:
MapperCacheInfo- Current cache statistics
var stats = Mapper.CacheInfo();
Console.WriteLine($"Total: {stats.Total}, Hit Ratio: {stats.HitRatio:P1}");Validates mapping configuration. Throws InvalidOperationException if unmapped properties exist.
Mapper.AssertMappingValid<User, UserDto>();-
Returns:
List<string>- Names of destination properties that cannot be mapped
var unmapped = Mapper.GetUnmappedProperties<User, UserDto>();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 byMaxCacheSize;Mapper.UseLruCacheapplies to the static mapper only.
Returns:
-
IDisposablemapper instance
Example:
using var mapper = MapperFactory.Create(new MapperOptions
{
MaxDepth = 16,
MaxCacheSize = 100,
Logger = Console.WriteLine
});
var dto = mapper.MapTo<UserDto>(user);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();-
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
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();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>- ContainsIsValid,Value,Errors,ErrorsByProperty
Example:
var result = mapper.MapAndValidate<User, UserDto, UserDtoValidator>(user);
if (result.IsValid) return result.Value;Maps source to destination and validates using a provided validator instance.
Example:
var validator = new UserDtoValidator();
var result = mapper.MapAndValidate<UserDto>(user, validator);Validates an existing object using the specified validator type.
Example:
var result = dto.Validate<UserDto, UserDtoValidator>();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);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: trueSets the logger every MapWithLogging call writes to, and routes Mapper.Logger to it.
SerilogExtensions.UseSerilog(Log.Logger, o => o.SlowMappingThreshold = TimeSpan.FromMilliseconds(50));Maps with timing, logged at Information. A failure is logged at Error and rethrown. Returns TDest?.
var dto = user.MapWithLogging<UserDto>();Maps a collection and logs the count and total time. Returns List<TDest>, empty for a null source.
var dtos = users.MapCollectionWithLogging<UserDto>();-
Type:
TimeSpan? -
Default:
null(no slow-mapping warnings)
Set through the configure action of UseSerilog.
Returns a MappingLoggingScope. Call RecordMapping() and RecordError() on it; disposing logs
the totals and elapsed time.
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();Async version of QueryAndMap.
Example:
var users = await connection.QueryAndMapAsync<User, UserDto>("SELECT * FROM Users");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 });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");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);Mapsicle
Packages
- Core
- Fluent
- EntityFramework
- Validation
- NamingConventions
- Serilog
- Dapper
- AspNetCore
- Json
- Caching
- Audit
- DataAnnotations
Reference