1

我有一个像这样的源类:

public partial class Source
{
    ...
    public int ScheduleBaseId { get; set; }
    public int ScheduleIncrement { get; set; }
    public int SubscriptionTypeId { get; set; } // <- Determines the concrete class to map to
    public string SubscriptionCriteriaJson { get; set; } // <- Map to interface class
    ...
}

我正在映射到这个目标类:

public class Dest
{
    ...
    public Schedule Schedule { get; set; }
    public ISubscriptionCriteria SubscriptionCriteria { get; set; }
    ...
}

我想将使用接口的Source.SubscriptionCriteriaJson属性映射到。Dest.SubscriptionCriteria可以使用来确定接口的具体类Source.SubscriptionTypeId。我试图在这里解决两个问题以映射到SubscriptionCriteria

  1. 将 json 字符串反序列化为ISubscriptionCriteria对象。
  2. 映射到ISubscriptionCriteria基于的正确具体类型SubscriptionTypeId

任何想法/指针我如何在 AutoMapper 中实现这一点?我是 AutoMapper 的新手,所以我仍然在摸索。

到目前为止,这就是我对其余映射的了解:

var config = new MapperConfiguration(
    cfg => cfg.CreateMap<Source, Dest>()
        .ForMember(dest => dest.Schedule, opt => { opt.MapFrom(src => new Schedule((ScheduleBaseEnum)src.ScheduleBaseId, src.ScheduleIncrement)); })
    );
4

1 回答 1

2

I solved this in the following way:

public class AutoMapperProfileConfiguration : Profile
{
    public AutoMapperProfileConfiguration()
        : this("MyProfile")
    {
    }

    protected AutoMapperProfileConfiguration(string profileName)
        : base(profileName)
    {
        CreateMap<Source, Dest>()
            .ForMember(dest => dest.Schedule, opt =>
            {
                opt.MapFrom(src => new Schedule((ScheduleBaseEnum)src.ScheduleBaseId, src.ScheduleIncrement));
            })
            .ForMember(dest => dest.SubscriptionCriteria, opt =>
            {
                opt.MapFrom(src => (ISubscriptionCriteria)JsonConvert.DeserializeObject(src.SubscriptionCriteriaJson, GetSubscriptionCriteriaType((SubscriptionTypeEnum)src.SubscriptionTypeId)));
            });
    }

    private Type GetSubscriptionCriteriaType(SubscriptionTypeEnum type)
    {
        switch (type)
        {
            case SubscriptionTypeEnum.SomeType1:
                return typeof(SomeType1);
            case SubscriptionTypeEnum.SomeType2:
                return typeof(SomeType2);
            ...
            default:
                throw new NotImplementedException(string.Format("SubscriptionType of {0} is not implemented.", Enum.GetName(typeof(SubscriptionTypeEnum), type)));
        }
    }
}

If there's a more elegant solution you can think of please share I'm keen to learn!

于 2017-07-14T03:24:36.830 回答