AutoMapper - 将Json字符串属性映射到基于接口的对象

时间:2017-07-14 02:02:27

标签: c# automapper automapper-6

我有这样的源类:

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的正确具体类型。
  3. 我是如何在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)); })
        );
    

1 个答案:

答案 0 :(得分:2)

我通过以下方式解决了这个问题:

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)));
        }
    }
}

如果有更优雅的解决方案,您可以想到请分享我热衷于学习!