AutoMapper之嵌套映射
8.嵌套映射
嵌套映射就是一个类中包含有另一个类,这种情况下我们应该如何映射呢?
/// <summary>
/// 源对象
/// </summary>
public class OuterSource
{
public int Value { get; set; }
public InnerSource Inner { get; set; }
}
/// <summary>
/// 源嵌套对象
/// </summary>
public class InnerSource
{
public int OtherValue { get; set; }
}
/// <summary>
/// 目标对象
/// </summary>
public class OuterDest
{
public int Value { get; set; }
public InnerDest Inner { get; set; }
}
/// <summary>
/// 目标嵌套对象
/// </summary>
public class InnerDest
{
public int OtherValue { get; set; }
}
/// <summary>
/// 嵌套映射测试类型
/// </summary>
[TestClass]
public class NestedMapping
{
[TestMethod]
public void NestedMappingTest()
{
//初始化
Mapper.Initialize(cfg => {
//指定外部类映射
cfg.CreateMap<OuterSource, OuterDest>();
//指定内部类映射
cfg.CreateMap<InnerSource, InnerDest>();
});
var src = new OuterSource
{
Value = 1,
Inner = new InnerSource { OtherValue =2}
};
OuterDest dest = Mapper.Map<OuterSource, OuterDest>(src);
//验证结果
Assert.AreEqual(1, dest.Value); //测试通过
Assert.IsNotNull(dest.Inner); //测试通过
Assert.AreEqual(2, dest.Inner.OtherValue); //测试通过
}
}
嵌套映射就这么简单,和正常的映射一样,只要指定映射的源类型和目标类型即可。