我有这样的源类:
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
的问题:
ISubscriptionCriteria
对象。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)); })
);
答案 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)));
}
}
}
如果有更优雅的解决方案,您可以想到请分享我热衷于学习!