Automapper Ignore property mapping – Guidelines
Today in this article we shall see how to map one object to another object using Automapper by ignoring unwanted fields.
AutoMapper is an object mapper that helps you transform one object of one type into an output object of a different type.
We already learned in our article on Getting started with Automapper in ASP.NET Core where we learned Automapper .NET 5 or .NET 6 configuration basics. We shall see Automapper Ignore property configuration.
Today in this article, we will cover below aspects,
Automapper profile dependency injection into the module
Dependency Injection of the IMapper interface is explained here already with more details,
Configuring Profile Instances
Here you need to create a class that inherits from the class Profile then please add your configuration of mapping into the Constructor. Profiles are one of the best ways of organizing all your mapping configurations in one place.
Automapper ignores property using ‘DoNotValidate‘
The below examples show how to Ignore property un Automapper using DoNotValidate.
Using DoNotValidate will Ignore the current member when validating source members.
public class SourceMappingProfile : Profile
{
public SourceMappingProfile()
{
CreateMap<Source, Destination>()
.ForMember(dest => dest.Employee, o => o.MapFrom(src => new[] { src.Employee }))
.ForSourceMember(source => source.Address, o => o.DoNotValidate())
.ForMember(dest => dest.Identity, o => o.MapFrom(src => src.Id));
}
Automapper ignores property using ‘Ignore‘
The below examples show how to Ignore property using the Automapper Ignore method.
Using Ignore will Ignore the current member when validating source members for configuration validation and skip during mapping.
public class SourceMappingProfile : Profile
{
public SourceMappingProfile()
{
CreateMap<Source, Destination>()
.ForMember(dest => dest.Employee, o => o.MapFrom(src => new[] { src.Employee }))
.ForMember(dest => dest.Location, o => o.Ignore())
.ForMember(dest => dest.Identity, o => o.MapFrom(src => src.Id));
}
References:
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.