0

我正在使用AutoMapper。 我的源對象是簡單的類AutoMapper將字符串映射到MS Dynamics CRM中的OptionSet值

public class Source 
    { 

     public string FirstName { get; set; } 

     public string type{ get; set; } 
} 

我的目標是MS 動態CRM實體(我已經生成使用CrmSvctil模型),其中包含一個選項設置命名類型

以下是我的映射

AutoMapper.Mapper.CreateMap<Source, Destination>() 
       .ForMember(dest => dest.type, opt => opt.MapFrom(src => src.type)); 

我得到錯誤類型不匹配

基本上我的問題是

我不知道如何使用字符串映射到選項設置值AutoMapper

回答

0

OptionSets存儲爲OptionSetValues,它具有Int類型的Value屬性,而不是字符串,因此您的類型不匹配錯誤。

如果你的類型是一個實際的INT,你只需要解析它:

AutoMapper.Mapper.CreateMap<Source, Destination>() 
      .ForMember(dest => dest.type, opt => opt.MapFrom(src => new OptionSetValue(int.parse(src.type)))); 

但如果它是在選項設置的實際文本值,則需要使用OptionSetMetaData查找文本值:

public OptionMetadataCollection GetOptionSetMetadata(IOrganizationService service, string entityLogicalName, string attributeName) 
{ 
    var attributeRequest = new RetrieveAttributeRequest 
    { 
     EntityLogicalName = entityLogicalName, 
     LogicalName = attributeName, 
     RetrieveAsIfPublished = true 
    }; 
    var response = (RetrieveAttributeResponse)service.Execute(attributeRequest); 
    return ((EnumAttributeMetadata)response.AttributeMetadata).OptionSet.Options; 
} 

var data = GetOptionSetMetadata(service, "ENTITYNAME", "ATTRIBUTENAME"); 
AutoMapper.Mapper.CreateMap<Source, Destination>() 
      .ForMember(dest => dest.type, opt => opt.MapFrom(src => new OptionSetValue(optionList.First(o => o.Label.UserLocalizedLabel.Label == src.type)))); 
相關問題