2012-07-27 110 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); 
} 
相關問題