AutoMapper:Unflattening to constructor

时间:2017-11-15 14:23:14

标签: c# automapper

假设我有以下课程

class Foo
{
    public Bar First { get; }

    public Bar Second { get; }

    public Foo(Bar first, Bar second)
    {
        First = first;
        Second = second;
    }
}

class Bar
{
    public string Name { get; set; }
}

class FooDto
{
    public string FirstName { get; set; }

    public string SecondName { get; set; }
}

我希望将FooDto映射到Foo。我读过关于Reverse Mapping and Unflattening的内容,所以我设置了这样的混淆:

IMapper mapper = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Foo, FooDto>()
        .ReverseMap();
}).CreateMapper();

不幸的是,

失败了
  

System.ArgumentException:Test.AutoMapper.Foo需要一个带有0个args或只有可选args的构造函数。

如何配置AutoMapper以使用Foo构造函数而无需手动映射所有构造函数参数? (在我的实际代码中,类型有更多属性)

2 个答案:

答案 0 :(得分:2)

您必须显式声明转换,因为构造函数参数和属性名称的名称不同。有关更多信息,请查看documentation

Here is a running example

public static void Main()
{
    var configuration = new MapperConfiguration(config =>
    {
        config.CreateMap<FooDto, Foo>()
            .ForCtorParam("first", opt => opt.MapFrom(src => src.FirstName))
            .ForCtorParam("second", opt => opt.MapFrom(src => src.SecondName));
        config.CreateMap<string, Bar>().ConvertUsing(value => new Bar() { Name = value });
    });

    var mapper = configuration.CreateMapper();
    var dto = new FooDto() { FirstName = "Hello", SecondName = "World" };

    var foo = mapper.Map<Foo>(dto);

    Console.WriteLine(foo.First.Name);
    Console.WriteLine(foo.Second.Name);
}

答案 1 :(得分:-1)

对于高于5.0的版本,请使用以下设置。

MapperConfiguration config = new MapperConfiguration(cfg =>
                {
                    cfg.CreateMap<SourceObjectType, DestinationObjectType>();
                    cfg.CreateMissingTypeMaps = true;
                    cfg.AllowNullCollections = true;
                    cfg.AllowNullDestinationValues = true;

                });