简体   繁体   English

AutoMapper将字符串映射到MS Dynamics CRM中的OptionSet值

[英]AutoMapper Map string to OptionSet value in MS Dynamics CRM

I am using AutoMapper. 我正在使用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 . 我的目的地是MS Dynamics CRM实体(我已经使用CrmSvctil生成了模型),其中包含名为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 我不知道如何使用AutoMapper将字符串映射到Option设置值

OptionSets are stored as OptionSetValues that have a Value Property of type Int, not Strings, hence your type mismatch error. OptionSet被存储为具有Set属性值类型为Int而不是字符串的OptionSetValues,因此您的类型不匹配错误。

If your type is an actual int, you just need to parse it: 如果您的类型是实际的int,则只需解析它:

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: 但是,如果它是选项集的实际文本值,则需要使用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))));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM