AutoMapper,映射不同类型的嵌套对象

本文关键字:嵌套 对象 同类型 映射 AutoMapper | 更新日期: 2023-09-27 18:03:31

CreateMap<SourceType, DestinationType>()
    .ForMember(dest => dest.Type3Property, opt => opt.MapFrom
    (
        src => new Type3
        { 
            OldValueType5 = src.oldValType6, 
            NewValueType5 = src.newValType6
        }
    );

在创建Type3时,我必须将Type6的嵌套属性分配给Type5。我怎么用Automapper来做呢?

AutoMapper,映射不同类型的嵌套对象

我们可能还需要一个更完整的例子来完全回答这个问题。但是…从目前你给我们的信息来看,我认为你只需要添加一个从Type6Type5的映射。

下面是一个映射这些"嵌套属性"的例子。你可以把它复制到控制台应用程序中运行。

class Program
{
    static void Main(string[] args)
    {
        var config = new MapperConfiguration(cfg =>
        {
            //The map for the outer types
            cfg.CreateMap<SourceType, DestinationType>()
                .ForMember(dest => dest.Type3Property, opt => opt.MapFrom(src => src.Inner));
            //The map for the inner types
            cfg.CreateMap<InnerSourceType, Type3>();
            //The map for the nested properties in the inner types
            cfg.CreateMap<Type6, Type5>()
                //You only need to do this if your property names are different
                .ForMember(dest => dest.MyType5Value, opt => opt.MapFrom(src => src.MyType6Value));
        });
        config.AssertConfigurationIsValid();
        var mapper = config.CreateMapper();
        var source = new SourceType
        {
            Inner = new InnerSourceType {
                OldValue = new Type6 { MyType6Value = 15 },
                NewValue = new Type6 { MyType6Value = 20 }
            }
        };
        var result = mapper.Map<SourceType, DestinationType>(source);
    }
}
public class SourceType
{
    public InnerSourceType Inner { get; set; }
}
public class InnerSourceType
{
    public Type6 OldValue { get; set; }
    public Type6 NewValue { get; set; }
}
public class DestinationType
{
    public Type3 Type3Property { get; set; }
}
//Inner destination
public class Type3
{
    public Type5 OldValue { get; set; }
    public Type5 NewValue { get; set; }
}
public class Type5
{
    public int MyType5Value { get; set; }
}
public class Type6
{
    public int MyType6Value { get; set; }
}