使用映射库将嵌套对象映射到 C# 中的自定义对象

我有以下对象结构:


/// <summary>

/// nested message instance provided by a business service

/// </summary>

public class Message

{

    public string Subject { get; set; }

    public DateTime CreationDate { get; set; }

    public List<Message> Messages { get; set; }

}

我想将该对象映射到以下对象结构:


/// <summary>

/// UI Object used to display a nested message structure

/// </summary>

public class MessageViewModel : ViewModelBase

{

    public bool IsSelected { get; set; }


    public string Subject { get; set; }


    public DateTime CreationDate { get; set; }

    public List<MessageViewModel> Messages { get; set; }

}

有没有可以轻松完成工作的映射器?


狐的传说
浏览 139回答 2
2回答

慕田峪7331174

我强烈推荐使用 Automapper,因为它非常简单易用。在 Automapper 中,默认情况下会映射具有相同名称的字段,并且需要最少的配置。您要实现的映射将按如下方式完成:&nbsp; var config = new MapperConfiguration(cfg =>&nbsp; {&nbsp; &nbsp; &nbsp; cfg.CreateMap<Message, MessageViewModel>();&nbsp; });在集合的情况下,Automapper 可以映射以下内容,前提是已为其数据类型定义了配置:IEnumerable收藏列表列表数组由于在您的情况下已经为列表的数据类型提供了映射,因此不需要进一步配置。如果您想映射具有不同名称的字段,或者您想在此过程中进行一些基本级别的验证,您可以使用以下语法来定义配置:var config = new MapperConfiguration(cfg =>{&nbsp; &nbsp; cfg.CreateMap<Message, MessageViewModel>()&nbsp; &nbsp; .ForMember(destination => destination.SomeDestinationField, map => map.MapFrom(source => source.SomeSourceFieldWithDifferentName))&nbsp; &nbsp; .ForMember(destination => destination.SomeDestinationField, map => map.MapFrom(source => source.SomeSourceField ?? SomeDefaultValue));});然后我们可以使用 MapperConfiguration 对象来初始化 Mapper 并执行我们的映射如下:SourceClass SourceObject = new SourceClass();// Populate SourceObject with valuesvar mapper = config.CreateMapper();DesitnationClass DestinationObject = mapper.Map<DesitnationClass>(SourceObject);我建议阅读这些文档。
打开App,查看更多内容
随时随地看视频慕课网APP