0

I have an example like this :

class Fields
{
    string ContactOneName{get;set;}
    string ContactOnePhone{get;set;}
    string ContactOneSpouseName{get;set;}
    string ContactOneSpousePhone{get;set;}
}

And I would like to map to a model like this:

class Contacts
{
    Contact ContactOne {get;set;}
    Contact ContactOneSpouse {get;set;}
}

class Contact
{
   string Name {get;set;}
   string Phone {get;set;}
}

There are lots of fields and I don't want to write a mapping for each field. Is this possible? If so how?

NB: This question is almost a duplicate of AutoMapper unflattening complex objects of same type but I want a solution NOT manually mapping everything, because in that case it is not worth using automapper.

Community
  • 1
  • 1
Myster
  • 17,704
  • 13
  • 64
  • 93

1 Answers1

0

You can take this and add:

public static IMappingExpression<TSource, TDestination> ForAllMembers<TSource, TDestination, TMember>(
    this IMappingExpression<TSource, TDestination> mapping,
    Action<IMemberConfigurationExpression<TSource, TDestination, TMember>> opt)
{
    var memberType = typeof(TMember);
    var destinationType = typeof(TDestination);

    foreach(var prop in destinationType.GetProperties().Where(prop => prop.PropertyType.Equals(memberType)))
    {
        var parameter = Expression.Parameter(destinationType);
        var destinationMember = Expression.Lambda<Func<TDestination, TMember>>(Expression.Property(parameter, prop), parameter);

        mapping.ForMember(destinationMember, opt);
    }

    return mapping;
}

Then you can configure the mapping as follows:

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Fields, Contacts>().ForAllMembers<Fields, Contacts, Contact>(x => { x.Unflatten(); });
});
Community
  • 1
  • 1
andres.chort
  • 836
  • 7
  • 9