C# AutoMapper - Set default value in dest property if not exist in source

Viewed 2668

I have:

Class A
{
    public string FirstName { get; set; }
}

Class B
{
    public string FirstName { get; set; }
    public Guid RequestId { get; set; }
}

I want to map from A to B, since "A" doesn't have RequestId I want to set it to Guid.NewGuid()

I tried this code:

var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<A, B>().ForMember(m => m.RequestId, o => Guid.NewGuid());
            
            });
            _mapper = config.CreateMapper();

But I'm still getting empty Guid in RequestId.

2 Answers

That mapping should look like this:

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<A, B>().ForMember(m => m.RequestId, o => o.MapFrom(s => Guid.NewGuid()));
        
});

Change mapping confugration:

cfg.CreateMapper<A,B>().ForMember(x => x.RequestId, o => o.NullSubstitute(Guid.NewGuid());
Related