0

I am using AutoMapper. My source object is simple class

public class Source
    {

        public string FirstName { get; set; }

        public string type{ get; set; }
}

My destination is a MS Dynamics CRM Entity ( I have generated the model using CrmSvctil) which contains an option set named type.

Following is my mapping

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

I am getting error is type mismatch

Basically my problem is

I don't know how to map string to an Option set value using AutoMapper

user2739679
  • 827
  • 4
  • 14
  • 24

1 Answers1

0

OptionSets are stored as OptionSetValues that have a Value Property of type Int, not Strings, hence your type mismatch error.

If your type is an actual int, you just need to parse it:

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

But if it's the actual text value for the option set, you'll need to lookup the text values using the 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))));
Daryl
  • 18,592
  • 9
  • 78
  • 145