开发者

Automapper: Resolve source property name from automapped object

开发者 https://www.devze.com 2023-03-14 00:01 出处:网络
Given the following classes: public class User { public int Id {get;set;} public PersonName Name {get;set;}

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 sou开发者_运维知识库rce property for a given property on the destination object:

something like:

Assert.AreEqual(GetSourcePropertyName<User, UserDto>("FirstName"), "Name.FirstName")


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消