使用自动映射器时如何将字段值从父级传递到嵌套对象?

时间:2019-04-03 10:29:28

标签: c# automapper

我正在尝试使用自动映射器映射对象。

我的输入模型:

public class Input
{
    public int ID { get; set; }
    public ICollection<NestedObject> NestedObjects { get; set; }
}
public class NestedObject
{
    public string SomeString { get; set; }
}

我的输出模型:

public class Output
{
    public int ID { get; set; }
    public ICollection<OutputNestedObject> OutputNestedObjects { get; set; }
}

public class OutputNestedObject
{
    public int InputID { get; set; }
    public string SomeString { get; set; }
}

我的映射代码:

[Test]
public void TestNesting()
{
    var mapper = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<Input, Output>()
            .ForMember(x=> x.OutputNestedObjects, src=> src.MapFrom(x=> x.NestedObjects))
            ;
    }).CreateMapper();

    var input = new Input()
    {
        ID = 111,
        NestedObjects = new List<NestedObject>()
        {
            new NestedObject(){SomeString = "sometext"},
        }
    };

    var output = mapper.Map<Output>(input);

    Assert.AreEqual(input.ID, output.ID);

    var inputNested = input.NestedObjects.First();
    var outputNested = output.OutputNestedObjects.First();

    Assert.AreEqual(input.ID, outputNested.InputID);
    Assert.AreEqual(inputNested.SomeString, outputNested.SomeString);

}

现在我有AutoMapperMappingException:

Unmapped properties: InputID

我想使用嵌套的OutputNestedObject和Input对象的ID获取Output的对象。这该怎么做?

谢谢!

2 个答案:

答案 0 :(得分:0)

您必须添加从NestedObjects到OutputNestedObjects的映射。

如果缺少某些属性,则Automapper不会在没有显式映射的情况下映射对象。

答案 1 :(得分:-1)

作为解决方法,我正在使用此解决方案:

var mapper = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<NestedObject, OutputNestedObject>();
    cfg.CreateMap<Input, Output>()
        .ForMember(x => x.OutputNestedObjects, src => src.MapFrom(x=> x.NestedObjects ))
        .AfterMap((src, dest) =>
        {
            foreach (OutputNestedObject nested in dest.OutputNestedObjects)
            {
                nested.InputID = src.ID;
            }
        })
        ;
}).CreateMapper();