如何对具有IEnumerable <t>属性</t>的ViewModel使用automapper

时间:2011-01-19 00:04:38

标签: asp.net-mvc unit-testing viewmodel automapper action-filter

我正在尝试关注Jimmy Bogard's advice for automapping through an actionfilter(在大多数情况下效果很好)。但是,如果我有一个自定义的viewmodel,我想要映射的集合属性呢?例如,

public class WidgetSearchViewModel
{
    public WidgetSearchOptionsViewModel Options { get; set; }
    public GenericListPagerViewModel Pager { get; set; }
    public IEnumerable<WidgetSearchResultModel> Results { get; set; }
}

Results属性来自存储库,作为IEnumerable域实体,我想使用automapper将其转换为WidgetSearchResultModel实例。问题是我需要在控制器中构建一个WidgetSearchViewModel来填充Options和Pager属性。如何使用AutoMapper ActionFilter填充Results属性OnActionExecuted?它是否可能,或者我是否需要在控制器中调用Mapper.Map调用并在我的单元测试中引导所有映射?

1 个答案:

答案 0 :(得分:2)

Automapper已经构建了对实现IEnumerable的任何嵌套集之间的映射的支持。如果定义父和子属性映射,则automapper将映射嵌套集合。

如果您实现CustomTypeConvertor,

Automapper还可以处理任何内容映射:http://automapper.codeplex.com/wikipage?title=Custom%20Type%20Converters&referringTitle=Home