0

I need to configure AutoMapper to Conditionaly map one target property to two different source properties:

public class JourneyDTO
{
  public VehicleDTO vehicle { get; set; }
}

public class Journey
{
  public Car car { get; set; }
  public Bus bus { get; set; }
}

public class Car
{
}

public class Bus
{
}

and then AutoMapper configuration:

.ForMember(m => m.vehicle, src => {
                    src.PreCondition(p => (p.bus != null));
                    src.MapFrom(f => f.bus);
                })

.ForMember(m => m.vehicle, src => {
                    src.PreCondition(p => (p.car!= null));
                    src.MapFrom(f => f.car);
                })

On my result JourneyDTO I only get vehicle filled with car. If there is no car, only bus on source object, then DTO vehicle property is null

Any hint?

Thanks!

Luke1988
  • 1,850
  • 2
  • 24
  • 42
  • I found a workaround, however trick ist to cast to object in order to compile – Luke1988 Oct 19 '20 at 12:12
  • Do not use ForMember method. If I remember well it is not recomending by Jimmy Bogard. Remove VehicleDTO and add CarDTO and BusDTO. If You are using NewtonSoft.Json to serialization You can ignore null values: https://stackoverflow.com/questions/6507889/how-to-ignore-a-property-in-class-if-null-using-json-net – Dawid Wekwejt Oct 19 '20 at 12:24
  • Why? What is a recommended replacement for ForMember method? – Luke1988 Oct 19 '20 at 12:36

1 Answers1

1

Solved:

.ForMember(
 m => m.vehicle, 
 src => src.MapFrom(o => ((o.bus != null) ? (object)o.bus : (object)o.car))
)
Luke1988
  • 1,850
  • 2
  • 24
  • 42