asp.net-mvc - 如何将自动映射器用于具有 IEnumerable<T> 属性的 ViewModel

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

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

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

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

最佳答案

Automapper 已经内置支持实现 IEnumerable 的任何嵌套集之间的映射。如果您定义父子属性映射,automapper 将映射嵌套集合就好了。

如果您实现了 CustomTypeConvertor,Automapper 还可以处理将任何内容映射到任何内容:http://automapper.codeplex.com/wikipage?title=Custom%20Type%20Converters&referringTitle=Home

关于asp.net-mvc - 如何将自动映射器用于具有 IEnumerable<T> 属性的 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4730458/

相关文章:

c# - 错误找不到指定的路径 - NuGet - ASP.NET MVC

c# - MVC 将自定义异常重新抛出为 JSON

swift - UI 测试包标识符和代码覆盖率

python - 如何在重新连接测试的单元测试中终止套接字

c# - 具有复杂属性的 ViewModel

java - 您可以使用空间而不使用 LiveData 对象吗?

javascript - 为 OnBeign 分配多个功能

c# - 在 ASP.NET MVC 中将多个表单从 View 传递到 Controller

python - 如何测试数据检索模块?

c# - MVC 自定义 View 模型问题