Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

SOLVED: Automapper one source multiple destionations and derived classes

Ahmet Keskin:

I am trying to map one entity object to different view models. I have a base view Model and two other view models that derive from the base. The view models are created based on their type property in run time via a factory method. There are no separate entities for the derived view models and source entity has all the properties for the derived view models. The problem is that Automapper is able to create the correct objects through the factory method but the properties in the derived objects are not mapped at all. Only the base view model's properties are mapped.

Sample entities:


public class VehicleEntity
{
public int Type { get; set; }
public int LoadCapacity { get; set; }
public TrailerEntity Trailer { get; set; }
}

public class TrailerEntity
{
public int Capacity { get; set; }
}

View models:


public class VehicleVM
{
public int Type { get; set; }
}

public class CarVM: VehicleVM
{
public TrailerVM Trailer { get; set; }
}

public class TruckVM : VehicleVM
{
public int LoadCapacity { get; set; }
}

public class TrailerVM
{
public int Capacity { get; set; }
}

public static class VehicleFactory
{
public static VehicleVM GetInstance(int type)
{
switch (type)
{
case 1:
return new CarVM();
case 2:
return new TruckVM();
default:
return new VehicleVM();
}
}
}

Finally the mapping:


List vehicleList = new List();
vehicleList.Add(new VehicleEntity()
{
Type = 1,
LoadCapacity = 0,
Trailer = new TrailerEntity()
{
Capacity = 120
}
});

vehicleList.Add(new VehicleEntity()
{
Type = 2,
LoadCapacity = 8000,
Trailer = null
});

var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap()
.ConstructUsing((Func)(rc => VehicleFactory.GetInstance(rc.Type)))
.Include()
.Include();
cfg.CreateMap();
cfg.CreateMap();
cfg.CreateMap();
});

IMapper mapper = config.CreateMapper();
var vehicleVMs = mapper.Map, List>(vehicleList);

In above example only the Type properties are mapped in CarVM and TruckVM. Other properties are not... I have also tried using ForMember method in order to map the derived Class properties from the source entity but no luck.


cfg.CreateMap().ForMember(dst => dst.LoadCapacity, opt => opt.MapFrom(src => src.LoadCapacity));

Is it possible to achieve this? Any help is appreciated.

Thank you.



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots


This post first appeared on Stack Solved, please read the originial post: here

Share the post

SOLVED: Automapper one source multiple destionations and derived classes

×

Subscribe to Stack Solved

Get updates delivered right to your inbox!

Thank you for your subscription

×