상세 컨텐츠

본문 제목

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.
 

728x90

https://automapper.org/

 

AutoMapper

What is AutoMapper? AutoMapper is a simple little library built to solve a deceptively complex problem - getting rid of code that mapped one object to another. This type of code is rather dreary and boring to write, so why not invent a tool to do it for us

automapper.org


Installation Instructions

In Visual Studio's Package Manager, you can install it by entering the following command.  Or you can install from NuGet.

Install-Package AutoMapper
 

Use Case

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

 

Getting Started Guide — AutoMapper  documentation

What is AutoMapper? AutoMapper is an object-object mapper. Object-object mapping works by transforming an input object of one type into an output object of a different type. What makes AutoMapper interesting is that it provides some interesting conventions

docs.automapper.org

 

728x90
반응형

관련글 더보기