开发者

In AutoMapper, is it possible to determine what the destination property name would be for a particular source property

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开发者_如何学Python: 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.


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);
 }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜