【问题标题】:Using Automapper to map a service result to a view model使用 Automapper 将服务结果映射到视图模型
【发布时间】:2012-07-27 20:50:12
【问题描述】:

我正在尝试将服务结果映射到特定视图模型。我有一个名为 Category 的实体,其中包含一个 Id 和一个名称。我通过存储库 ICategoryRepository 公开它。我有一个服务 IInfrastructureService,它使用类别存储库来获取所有类别。 GetAllCategories 返回一个 IList。在我的 MVC 项目中。我有一个名为 NavigationController 的控制器。此控制器需要调用 GetAllCategories 服务。我想把这个结果映射成这样的结构:

public class CategoryViewModel {
    public Guid CategoryId { get; set; }
    public string Name { get; set; }
}

public class CategoryMenuViewModel {
    public IList<CategoryViewModel> Categories { get; set; }
    public CategoryViewModel SelectedCategory { get; set; }
}

我想使用 Automapper 来执行此操作。在我的 Application_Start() 中,我创建了地图:

Mapper.CreateMap<Category, CategoryViewModel>();

然后在我的控制器中:

public ViewResult CategoryMenu()
{
    CategoryMenuViewModel viewModel = new CategoryMenuViewModel();
    Mapper.CreateMap<Category, CategoryViewModel>();
    viewModel.Categories = Mapper.Map<IList<Category>, IList<CategoryViewModel>>(_infrastructureService.GetAllCategories());
    return View(viewModel);
}

这给了我这个例外:程序集中的类型名称重复。

我不确定我在这里做错了什么。任何帮助或指导都会动摇!

【问题讨论】:

    标签: asp.net-mvc domain-driven-design automapper


    【解决方案1】:

    你为什么在你的控制器中调用Mapper.CreateMap?这应该在 AppDomain 的整个生命周期内只调用一次,最好是在 Application_Start 中。在控制器内部,您只能调用 Mapper.Map 方法。

    您收到异常的原因是您已经在 Application_Start 中定义了 Category 和 CategoryViewModel 之间的映射 (.CreateMap)。所以:

    public ViewResult CategoryMenu()
    {
        var categories = _infrastructureService.GetAllCategories();
        CategoryMenuViewModel viewModel = new CategoryMenuViewModel();
        viewModel.Categories = Mapper.Map<IList<Category>, IList<CategoryViewModel>>(categories);
        return View(viewModel);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多