'AutoMapper ProjectTo not loading navigation properties for conditional mapping

I have the following mapping for a property

.ForMember(x => x.Destination, opt => opt.MapFrom(x =>
                x.Request.PurposeId == (int)PurposeTypes.PickUpShipment
                    ? x.Request.RequestDestinations.FirstOrDefault().Destination
                    : x.Request.ShippingDestinationDetails.FirstOrDefault(dd => dd.ShippingAddressTypeId == (int)ShippingRequestAddressType.Destination).ShippingAddress.Destination
            ))

And the destination object map is like this

CreateMap<Destination, DestinationDTO>()
.ForMember(x => x.LocationCode, opt => opt.MapFrom(x => x.LocationCode))
.ForMember(x => x.CountryCode, opt => opt.MapFrom(x => x.CountryCode))
.ForMember(x => x.CountryName, opt => opt.MapFrom(x => x.State.StateShortName)); // this is not working

The problem is when I am using ProjectTo the CountryName is not loading because it is not loading the navigation property State of the destination, so x.State.StateShortName is coming empty.

And I found out the reason behind it, this is happening because I am loading the destination conditionally and because of this it is not loading the navigation property, because if I remove the condition and loads the destination like this it works

.ForMember(x => x.Destination, opt => opt.MapFrom(x =>
        x.Request.RequestDestinations.FirstOrDefault().Destination
))

So basically ProjectTo is not loading the navigation property if the property mapping is conditional and not direct.

Is there any way I can achieve this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source