views:

54

answers:

1

Note: the question relates to the mapping meta-data, not the mapped values. i.e. what is the NAME of the target mapped property, not the mapped value.

Background: I'm using MVC 2 with automapper to map between domain entities and view models. I have some validation rules at the domain level which are defined in the domain model, and some more ui-specific validation rules defined in the view models using data annotations. In the interest of staying DRY, I don't want to have to repeat my domain validation rules in the view models. Instead, I'd like to be able to map the property names in the domain model to their corresponding property names in the view models using the mapping information I have already set up in AutoMapper. The domain validation errors would then be added to the ModelState using ModelState.AddModelError(), to be displayed on the view.

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

A: 
Mapper.GetAllTypeMaps()
  .First(x=>x.SourceType==typeof(CustomType))
  .DestinationType.Name

Untested, 'works' 1 lvl deep only and most likely just fails. But might 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);
 }
Arnis L.
That will give the name of the target type for a particular source type. I'm after the name of the target property for a particular source property. E.g. if MyAddress.AddressLine1 maps to OtherAddress.ResidentialAddress.AddressLine1, then I would like to be able to pass in "AddressLine1" into a function and have it return "ResidentialAddress.AddressLine1"
Teevus