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

时间:2016-08-23 12:56:31

标签: c# .net automapper

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

创建Type3时,我必须将Type6的嵌套属性分配给Type5。我如何使用Automapper进行操作。

1 个答案:

答案 0 :(得分:1)

我们可能仍需要一个更完整的例子才能完全回答这个问题。但是......从你到目前为止给我们的内容来看,我认为你只需要添加从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; }
}
相关问题