In AutoMapper, you can determine what the name of the destination property will be for a specific source property

Note. The question is about display metadata, not the displayed values. that is, what is the NAME of the target mapped property, not the displayed value.

Background: I am using MVC 2 with automapper to map between domain entities and view models. I have some domain-level validation rules that are defined in the domain model, and some more ui-specific validation rules defined in the presentation models using data annotations. In the interest of staying DRY, I do not want to repeat the domain validation rules in view models. Instead, I would like to map the property names in the domain model to their corresponding property names in the view models, using the mapping information that I already set in AutoMapper. Domain validation errors will then be added to ModelState using ModelState.AddModelError (), which will be displayed in the view.

The property names in the validation messages must match so that MVC can display the message next to the correct control on the form.

+3
source share
1 answer
Mapper.GetAllTypeMaps()
  .First(x=>x.SourceType==typeof(CustomType))
  .DestinationType.Name

Untested, "works" only at 1 lvl and, most likely, just fails. But it can give some ideas:

 public static string Get<T,TProp>(this T o,Expression<Func<T,TProp>> prop){
      var pn=((MemberExpression)prop.Body).Member.Name;
      var dt=Mapper.GetAllTypeMaps()
        .First(x=>x.SourceType==typeof(T));
      var pmaps=dt.GetPropertyMaps();
      var dpmap=pmaps.First(x=>x.DestinationProperty.Name==pn);
      return string.Format("{0}.{1}", //hyper dirty lol
        dt.DestinationType.Name,dpmap.DestinationProperty.Name);
 }
0
source

Source: https://habr.com/ru/post/1762244/


All Articles