1 Introduction
TinyMapper is a .Net object-to-object mapper. The main advantage is performance.
TinyMapper allows easy mapping of objects to objects, that is, properties or fields from one object to another.
TinyMapper is simple to use, with only Bind and Mapper operations; and the supported configuration is also very simple.
TinyMapper supports versions above .Net 3.0
2. Website
3. Use
3.1, installation
Through the console
PM> Install-Package TinyMapper
or
3.2, use steps
1. Binding mapping relationship
public static void Bind<TSource, TTarget>();
//或者
public static void Bind<TSource, TTarget>(Action<IBindingConfig<TSource, TTarget>> config);
2. Perform mapping
Note: The mapping object of TinyMapper must be of Public type.
public static TTarget Map<TTarget>(object source);
//或者
public static TTarget Map<TSource, TTarget>(TSource source, TTarget target = default(TTarget));
4, concrete case
Create two mapping objects:
public class Product
{
public Guid Id {
get; set; }
public string Name {
get; set; }
public decimal Price {
get; set; }
}
public class ProductDTO
{
public Guid Id {
get; set; }
public string Name {
get; set; }
public decimal Price {
get; set; }
}
Binding and execution
From product to ProductDTO
var product = new Product()
{
Id = Guid.NewGuid(),
Name = "Product" + DateTime.Now.Ticks,
Price = 12
};
//1. 创建映射关系
TinyMapper.Bind<Product, ProductDTO>();
//2. 执行映射
var productDto = TinyMapper.Map<ProductDTO>(product);
5. Collection mapping
var products = new List<Product>()
{
new Product()
{
Id = Guid.NewGuid(),
Name = "Product" + DateTime.Now.Ticks,
Price = 5
},
new Product()
{
Id = Guid.NewGuid(),
Name = "Product" + DateTime.Now.Ticks,
Price = 10
}
};
//1. 创建映射关系
TinyMapper.Bind<List<Product>, List<ProductDTO>>();
//2. 执行映射
var productDtos = TinyMapper.Map<List<Product>>(products);
When performing mapping conversion, TinyMapper does not support interface types: IList, ICollection, IEnumerable.
6. Specify fields
Give the Price field to Money
//1. 创建映射关系
TinyMapper.Bind<Product, ProductDTO>(cfg =>
{
cfg.Bind(src => src.Price, dest => dest.Money); //指定字段映射
});
//2. 执行映射
var productDto = TinyMapper.Map<ProductDTO>(product);
7. Ignore the specified field
TinyMapper.Bind<Product, ProductDTO>(cfg =>
{
cfg.Ignore(src => src.Price); //映射时不管某些字段
});
Note: By default, TinyMapper will map based on the field name, regardless of the field type. In other words, if the source object field name is the same as the target object field name, but the type is inconsistent and cannot be coerced, an exception will be thrown.
Efficient mapping method for manual conversion of fields with the same name by referring to URL