2012-07-27 113 views
1

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

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); 
} 

这是给我这个例外:一个组件中有重复的类型名。

我不知道我在做什么错在这里。任何帮助或指导都会摇滚!

回答

5

为什么在控制器内部拨打Mapper.CreateMap?这应该只在AppDomain的整个生命周期中调用一次,理想情况下在Application_Start。在控制器内部,您只能调用Mapper.Map方法。

您得到异常的原因是因为你已经定义在你的Application_Start类别和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); 
} 
相关问题