0

我正在使用 AutoMapper。我的源对象是简单的类

public class Source
    {

        public string FirstName { get; set; }

        public string type{ get; set; }
}

我的目的地是一个 MS Dynamics CRM实体(我使用CrmSvctil生成了模型),其中包含一个名为type的选项集

以下是我的映射

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

我收到错误是类型不匹配

基本上我的问题是

我不知道如何使用 AutoMapper 将字符串映射到选项集值

4

1 回答 1

0

OptionSets 存储为具有 Int 类型的值属性的 OptionSetValues,而不是字符串,因此您的类型不匹配错误。

如果你的类型是一个实际的 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))));
于 2014-03-26T16:50:48.110 回答