automapper ignore in csharp

To ignore a property during object mapping using AutoMapper in C#, you can use the ForMember() method in the MapperConfiguration class.

Here's an example:

main.cs
public class Source
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

public class Destination
{
    public int Id { get; set; }
    public string Name { get; set; }
}

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Source, Destination>()
        .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id))
        .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name))
        .ForMember(dest => dest.Description, opt => opt.Ignore()); // ignore Description property
});

IMapper mapper = config.CreateMapper();
var source = new Source { Id = 1, Name = "Test", Description = "Description" };
var destination = mapper.Map<Source, Destination>(source);
752 chars
25 lines

In the above example, the Description property from the Source class is ignored during object mapping to the Destination class using the ForMember() method with the opt.Ignore() statement.

gistlibby LogSnag