Nivitha Gopalakrishnan
Nivitha Gopalakrishnan

Reputation: 659

How to configure Automapper to ignore Object-Properties if properties is null but map if not null

I am using Automapper. In that, I mapped the DTO objects with another object.

UserProperties Class.

public string DisplayName { get; set; }

public int Id { get; set; }

public int NotesCount {get;set;}

PersonsDTO class

public string UserName { get; set; }

public int UserId { get; set; }

public int NotesCount { get ; set; }

public int BooksCount { get; set; }

Persons class

public UserProperties? UserDetails { get; set; }

public int NotesCount { get ; set; }

public int BooksCount { get; set; }

In Mapping Profile,

CreateMap<PersonsDTO, Persons>()
             .ForPath(o => o.UserDetails.DisplayName, b => b.MapFrom(z => z.UserName))
             .ForPath(o => o.UserDetails.Id, b => b.MapFrom(z => z.UserId))
             .ReverseMap();

In my case, UserDetails in the Persons class is a nullable type. If UserId in the PeronsDTO class is 0 means, I no need to map UserDetails. It should returns as null for the UserDetails property.

How can I achieve it?

Automapper Version: 9.0.0

Upvotes: 0

Views: 290

Answers (1)

Dillon Drobena
Dillon Drobena

Reputation: 921

You can specify a custom resolver to explicitly do your custom mapping.

    CreateMap<PersonDTO, Person>()
      .ForMember(dest => dest.UserDetails, opt => opt.MapFrom<CustomResolver>());

    public class CustomResolver : IValueResolver<PersonDTO, Person, UserProperties>
    {
        public UserProperties Resolve(PersonDTO source, Person destination, UserProperties member, ResolutionContext context)
        {
            if (source.UserId == 0)
                return null;
            return new UserProperties
            {
                DisplayName = source.UserName,
                Id = source.UserId
            };
        }
    }

Upvotes: 1

Related Questions