Automapper: resolve the name of a source property from an automatic object

Given the following classes:

public class User
{
  public int Id {get;set;}
  public PersonName Name {get;set;}
}

public class PersonName 
{
  public string FirstName {get;set;}
  public string LastName {get;set;}
}


public class UserDto 
{
  public int Id {get;set;}
  public string FirstName {get;set;}
}

And the following display configuration:

 Mapper.CreateMap<User, UserDto>()
            .ForMember(destination => destination.FirstName, 
            options => options.MapFrom(source => source.Name.FirstName))

Is it possible to resolve the name of the source property for this property in the target:

sort of:

Assert.AreEqual(GetSourcePropertyName<User, UserDto>("FirstName"), "Name.FirstName")
+5
source share
1 answer

Since MapFrom () accepts lambda, it is possible that the destination property maps to anything. You can use any lambda you want. Consider this:

.ForMember(
    destination => destination.FullName,  
    options => options.MapFrom(source => source.Name.FirstName + " " + source.Name.LastName)
);

Since you are not forced to create a simple lambdas property accessory, you cannot reduce the original expression to a simple property name string.

MapFrom() Expression<Func<TSource, TMember>>, , , .

+7

All Articles