Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper: Resolve source property name from automapped 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 mapping 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 a given property on the destination object:

something like:

Assert.AreEqual(GetSourcePropertyName<User, UserDto>("FirstName"), "Name.FirstName")
like image 933
Paul Avatar asked Jun 20 '11 15:06

Paul


1 Answers

Because MapFrom() takes a lambda, it's possible that the destination property is mapped 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)
);

Because you're not forced to make simple property accessor lambdas, you can't reduce the source expression to a simple property name string.

If MapFrom() took Expression<Func<TSource, TMember>> it would be possible to turn the expression into a string, but it can't be done the way it's currently written.

like image 55
Patrick Hallisey Avatar answered Sep 26 '22 11:09

Patrick Hallisey