How to handle custom Properties in AutoMapper

前端 未结 3 1515
被撕碎了的回忆
被撕碎了的回忆 2020-12-14 08:05

I\'ve got a ViewModel that takes some Model data and slightly alters it.

The way I\'m doing it \"works\" since I just pass the DomainModel to the constr

3条回答
  •  旧时难觅i
    2020-12-14 08:30

    On automapper where you create the Map you can specify additional processes for specific members of the destination type.

    So where your default map would be

    Mapper.Map();
    

    there is a fluent syntax to define the more complicated mappings:

    Mapper.Map()
          .ForMember(vm=>vm.UserName, m=>m.MapFrom(u=>(u.UserName != null) 
                                                   ? u.UserName 
                                                   : "User" + u.ID.ToString()));
    

    Here the ForMember takes two Arguments the first defines the property that you are mapping to. The second provides a means of defining the mapping. For an example I have copped out and shown one of the easy mappings.

    If you require a more difficult mapping, (such as your CurrentUser mapping) you can create a class that implements the IResolver interface, incorporate your mapping logic in that new clases and then add that into the mapping.

    Mapper.Map()
      .ForMember(vm=>vm.IsUserMatch, m=>m.ResolveUsing()));
    

    when Mapper comes to do the mapping it will invoke your custom resolver.

    Once you discover the syntax of the .ForMember method everything else kind of slots into place.

提交回复
热议问题