我一直在将领域对象展开为DTO,如下所示的示例:
public class Root
{
public string AParentProperty { get; set; }
public Nested TheNestedClass { get; set; }
}
public class Nested
{
public string ANestedProperty { get; set; }
}
public class Flattened
{
public string AParentProperty { get; set; }
public string ANestedProperty { get; set; }
}
// I put the equivalent of the following in a profile, configured at application start
// as suggested by others:
Mapper.CreateMap<Root, Flattened>()
.ForMember
(
dest => dest.ANestedProperty
, opt => opt.MapFrom(src => src.TheNestedClass.ANestedProperty)
);
// This is in my controller:
Flattened myFlattened = Mapper.Map<Root, Flattened>(myRoot);
我查看了很多示例,目前似乎这是展开嵌套层次结构的方法。但是,如果子对象有许多属性,则此方法并没有节省太多编码。
我找到了这个例子:
但它需要映射对象的实例,由Map()函数所需,这在我理解中无法与配置文件一起使用。
我是AutoMapper的新手,想知道是否有更好的方法来做到这一点。
AfterMap
不再接受上下文。我们可能需要使用IMappingAction
: https://docs.automapper.org/en/stable/Before-and-after-map-actions.html - David Liang