Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapping List with Default Values

Tags:

c#

automapper

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

like image 718
frictionlesspulley Avatar asked Jun 18 '12 15:06

frictionlesspulley


1 Answers

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
          }
       });
like image 57
Steve Czetty Avatar answered Nov 09 '22 12:11

Steve Czetty