I've got a recursive model class with the following definition:
public class ItemFilterBlockGroup
{
public ItemFilterBlockGroup(string groupName, ItemFilterBlockGroup parent, bool advanced = false)
{
GroupName = groupName;
ParentGroup = parent;
Advanced = advanced;
ChildGroups = new List<ItemFilterBlockGroup>();
}
public string GroupName { get; private set; }
public bool Advanced { get; private set; }
public ItemFilterBlockGroup ParentGroup { get; private set; }
public List<ItemFilterBlockGroup> ChildGroups { get; private set; }
}
It has a property called ChildGroups which is a list of itself - this is used to build up a hierarchical model. What I'm trying to do is map this model to view models, but conditionally. Sometimes (depending on a UI setting) I want to include only Child objects with Advanced = false, and sometimes I want to include all models.
Currently I'm achieving this with a nasty hack that involves Mapper.Reset() and runtime re-definition of the maps - this is obviously not good and presents multiple problems:
Mapper.Reset();
if (showAdvanced)
{
Mapper.CreateMap<ItemFilterBlockGroup, ItemFilterBlockGroupViewModel>();
}
else
{
Mapper.CreateMap<ItemFilterBlockGroup, ItemFilterBlockGroupViewModel>()
.ForMember(dest => dest.ChildGroups,
opts => opts.MapFrom(from => from.ChildGroups.Where(c => c.Advanced == false)));
}
var mappedViewModels = Mapper.Map<ObservableCollection<ItemFilterBlockGroupViewModel>>(blockGroups);
Given an example input hierarchy of models:
Root (Advanced = False)
+-Child 1 (Advanced = True)
+-Child 2 (Advanced = False)
+-Child 3 (Advanced = False)
+-Child 3 Sub Child 1 (Advanced = False)
+-Child 3 Sub Child 2 (Advanced = True)
The first CreateMap definition returns this hierarchy untouched, and the second CreateMap definition (with the Advanced parameter) returns this modified hierarchy (all Advanced = true models and their children are excluded from mapping):
Root (Advanced = False)
+-Child 2 (Advanced = False)
+-Child 3 (Advanced = False)
+-Child 3 Sub Child 1 (Advanced = False)
How can I parameterise the showAdvanced condition and achieve the same result with a single CreateMap definition? I've searched a lot for the right solution, tried ResolveUsing, CustomResolvers, to no avail.