My problem can be reduced to basically the following set of entities :
I have an entity say : MyEntity
which has a list of EntityTiming
(named Timings)
public class Entity{
public List<EntityTiming> Timings {get;set;}
}
It corresponds to a ViewModel : MyEntityViewModel
which has a list of TimingViewModel
(named Timings).
public class EntityViewModel
{
public IList<TimingViewModel> Timings {get;set;}
}
I have the following rules configured for mapping the direction : entity -> viewModel
Mapper.CreateMap<Entity,EntityViewModel>
Mapper.CreateMap<EntityTiming,TimingViewModel>
The EntityViewModel.Timings MUST have 7 items. However the Enitity.Timings might have less than 7 items / never more.
My Question is : is there a way to provide default values if the item is null in the listing using AutoMapper
You can use AfterMap()
:
Mapper.CreateMap<Entity, EntityViewModel>()
.AfterMap((src, dest) => {
if (dest.Timings == null) {
// Populate default values
}
else if (dest.Timings.Count < 7) {
// Populate the rest of the values
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With