我一直在将域对象扁平化为 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 的新手,所以我想知道是否有更好的方法来做到这一点。