Search code examples
c#linqautomapper

Linq set null to a value with automapper


I have a ticket that contains messages. Also, the ticket model contains a a resolutionMessage that is a message that can be nullable.

I want to do something like that :

Mapper.CreateMap<Ticket, TicketModel>()
.ForMember(dest => dest.ResolutionMessage, opt => opt.MapFrom(src => 
            {

                if (src.ResolutionMessageID != null)
                {
                    src.Messages.Where(m => m.MessageID == src.ResolutionMessageID);
                }
                else
                    // Return null;
                }
                ));

Second attempt :

            .ForMember(dest => dest.ResolutionMessage, opt =>
                {
                     (opt.MapFrom(src => if(src.ResolutionMessageID != null) 
                      opt.MapFrom(src => src.Messages.Where(m => m.MessageID == src.ResolutionMessageID));
                else
                    opt => opt.Ignore();
                }

                );

Any ideas?


Solution

  • I will consider ResolutionMessageID is a nullable type, you can try something like this:

    .ForMember(dest => dest.ResolutionMessage, opt => opt.MapFrom(src => src.ResolutionMessageID.HasValue ? src.Messages.Where(m => m.MessageID == src.ResolutionMessageID) : null));
    

    If it is not a nullable type and allow null:

    .ForMember(dest => dest.ResolutionMessage, opt => opt.MapFrom(src => src.ResolutionMessageID != null ? src.Messages.Where(m => m.MessageID == src.ResolutionMessageID.Value) : null));
    

    Or you use opt.MapFrom() or opt.Ignore(), there is not way to use both. I think it is better keep the null value when the condition for you map does not accept the rule. If you use, opt.Ignore() will ignore the property on conversion of objects.