Automapper How to set another property if source is null

Cenk 951 Reputation points
2022-08-10T08:44:32.9+00:00

Hello,

I wonder if there is a way to set Pin to Serial if Pin is null.

CreateMap<CouponDto, Coupon>()  
                .ForMember(dest => dest.Pin, src => src.NullSubstitute("-"))  
                .ForMember(dest => dest.Serial, src => src.NullSubstitute("-"));  
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,198 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
293 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Laxmikant 216 Reputation points
    2022-11-07T13:51:57.473+00:00

    you can use IValueResolver to implement custom mapping

    public class CustomPropertyMapping  
            : IValueResolver<Source, Destination, int>  
        {  
            public decimal Resolve(Source source,   
                DestinationDto destination, int value,   
                ResolutionContext context)  
            {  
                 if (condition met)  
                    return property1;  
                else   
                    return property2  
            }  
        }  
    

    and in configuration

    CreateMap>Source, DestinationDto>()  
        .ForMember(dest => dest.property,   
            source => source.MapFrom<CustomPropertyMapping>())  
    

    for more details on see custom property mapping using AutoMapper

    0 comments No comments