billybob
billybob

Reputation: 2998

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?

Upvotes: 6

Views: 5647

Answers (2)

Dev-lop-er
Dev-lop-er

Reputation: 728

Try using AfterMap MappingExpression in AutoMapper and then check for null value.

  • AfterMap(Action<TSource, TDestination> afterFunction);

Example:

 // Execute a custom function to the source and/or destination types after member mapping

CreateMap<Resource, SubjectResource>()
.AfterMap((src, dest) =>
              {
                if (src.Subject.English == null)
                {
                  dest.Subject.English = Enumerable.Empty<SubjectResourceList>();
                }
              });

Upvotes: 1

Felipe Oriani
Felipe Oriani

Reputation: 38598

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.

Upvotes: 3

Related Questions