Getting Started¶
Syntax to perform mapping:
mapper.Map<TOutput>(TInput input);
TOutput is our destination type and TInput is our source one.
Initialization¶
A mapper requires a provider to be instantiated.
IMappingProvider provider = new Output.Providers.MappingProvider();
IMapper mapper = new Mapper(provider);
Entities to respectives DTOs¶
Given our entities:
public class Product
{
public Guid Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
public ProductCategory Category { get;set; }
}
public class ProductCategory
{
public Guid Id { get; set; }
public string Name { get; set; }
}
And our DTOs:
public class ProductDto
{
public Guid Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
public ProductCategoryDto Category { get;set; }
}
public class ProductCategoryDto
{
public Guid Id { get; set; }
public string Name { get; set; }
}
Sample:
var product = new Product()
{
Id = Guid.NewGuid(),
Name = "Coffee",
IsActive = true,
Category = new ProductCategory()
{
Id = Guid.NewGuid(),
Name = "Heaven's Goods"
}
}
var mapper = new Mapper(new MappingProvider());
// performing the mapping
mapper.Map<ProductDto>(product);
Transforming to a flat DTO¶
You can also transform the TInput The source type nested objects to a flatten TOutput The destination type one.
// ... previous code above
public class ProductFlatDto
{
public Guid Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
public string CategoryId { get; set; }
public string CategoryName { get; set; }
}
mapper.Map<ProductFlatDto>(product);
Read more about Flattening & Unflattening.
Existing TOutput object¶
You can also pass a instance of the TOutput The destination type as the second parameter of the Map’s method.
var dto = new ProductDto();
mapper.Map(product, dto);
Internally it uses this already instantiated object to perform the mappings.
See also Map Chain.