2016-12-02 53 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对象,以便我可以查找属性中包含我的错误消息的一些自定义属性。