.NET Auto Mapper library

The Auto Mapper library is very practical and useful for mapping between view models and models, so that only a subset of properties is projected or manipulated somehow.

https://automapper.org/

For instance if we want to accept a password in a view model but not to return it back.

Everything is automatic, no need to add new code for new fields unless they should be treated in a special way.

It natively supports .NET core dependency injection.

Here is a simple setup:

Create a profile by extending the "Profile" class:

public class AutoMapperProfile: Profile
{
    public AutoMapperProfile()
    {

        CreateMap<MyModelView, MyModel>()
            .ForMember(v => v.ModifyDate, opt => opt.Ignore())
            .ForMember(v => v.Id, opt => opt.Ignore())
            .ForMember(v => v.Name, opt => opt.Ignore())
            .ReverseMap();
    }
}

This configuration ignores the three fields of the view during the conversion, however maps everything in the opposite direction.

In the startup.cs file add the mapper service:

services.AddAutoMapper(typeof(AutoMapperProfile));

Then inject the IMapper instance in the controller or wherever you want.




Post a Comment

Previous Post Next Post