2016-12-02 30 views
0

一個屬性我使用AutoMapper到我的MVC ViewModels映射到DTO,然後再返回,並想知道是否有可能利用從AutoMapper一個TypeMap僅經由屬性映射值名稱?使用Automapper.TypeMap映射的名字

我的情況是這樣的:

  1. 我通過Automapper映射ViewModelDTO
  2. 我通過WCF調用發送DTO,驗證失敗。
  3. 我得到一個FaultException回來,失敗的DTO字段的名稱。
  4. 我需要設置ModelState字典,其中ViewModel屬性的名稱失敗,並顯示錯誤消息。這使我可以突出顯示屏幕上的錯誤字段。

所以我的問題在於,能夠映射失敗,回到ViewModel屬性DTO屬性的string名稱。我想這樣做:

var typemap = Mapper.FindTypeMapFor(typeof(DTO), typeof(Model)) 
string erroredPropertyName = "Prop1"; // Really extracted from my Fault 

// This is the bit that doesn't exist, and I need help with...... 
// string destination = typemap.GetDestinationFor(erroredPropertyName); 

ModelState.Add(destination, errorMessage); 

這是可能的嗎?如果需要,我不介意使用Reflection,但如果可以的話,我寧願不使用它。

回答

0

我發現通過AutoMapper到底這樣做的一個很好的方式:

public PropertyInfo MapDestinationPropertyNameToSourceProperty<TSource, TDestination>(string propertyName) 
    { 
     var typeMap = GetTypeMap<TSource, TDestination>(); 

     var sourcePropName = typeMap.GetPropertyMaps().Where(m => m.DestinationProperty.Name == propertyName).Select(x => x.SourceMember.Name).FirstOrDefault(); 
     if (string.IsNullOrWhiteSpace(sourcePropName)) 
      return null; 

     return typeMap.SourceType.GetProperties().FirstOrDefault(n => n.Name == sourcePropName);    
    } 

這讓我在目標屬性的名稱通過,並返回它映射到的財產PropertyInfo從。

我可能剛剛返回了源屬性名稱,但是我想要完整的PropertyInfo對象,以便我可以查找屬性中包含我的錯誤消息的一些自定義屬性。