Easy Guide to AutoMapper (Simple Class Converter) - C# & .NET
While you are creating numerous classes during development, there are numerous cases where you have to convert from one to another classes. For example, you may want to convert classes generated by Entity Framework to a class for use with Web API or client application. Many cases you may include same property names.
During this process, you may be writing extra codes to convert from one to another class. AutoMapper will help you minimize number of repetitive lines of conversion codes you write.
In Visual Studio's Package Manager, you can install it by entering the following command. Or you can install from NuGet.
Install-Package AutoMapper
You will need a mapper configuration first (shown as example below). Create a new mapper configuration with the source and destination class. The example below is to convert from Order to OrderDto class.
var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDto>());
var mapper = new Mapper(config);
OrderDto dto = mapper.Map<OrderDto>(order);
By default, it will only map the propeties with the same names. If you want to map different property names, use Linq to map names as example shown below:
var config = new MapperConfiguration(
cfg => cfg.CreateMap<Order, OrderDto>().ForMember(
dest => dest.OrderName,
opt => opt.MapFrom(src => src.OrderTitle)));
var mapper = new Mapper(config);
OrderDto dto = mapper.Map<OrderDto>(order);
The code above will map OrderTitle in the source class (Order) to OrderName in the destination class (OrderDto).
Simple enough, right?
https://docs.automapper.org/en/latest/Getting-started.html
Static Method Using "this" Parameter - C# & .NET (0) | 2023.03.09 |
---|---|
Easily Create a Modal Dialog Box with Callbacks - JavaScript (0) | 2023.03.01 |
Tips for Performance Improvement - Visual Studio (0) | 2023.02.26 |
Persisting Grafana and Prometheus Configuration Data - Kubernetes (0) | 2023.02.20 |
Adding SSL to Grafana and Accessing It from Anywhere - Kubernetes (0) | 2023.02.20 |