Reputation: 47
I have NewsViewModel
, which includes :
public class CategoryViewModel
{
public CategoryViewModel()
{
List = new List<CategoryModel>();
}
public IEnumerable<CategoryModel> List { get; set; }
public CategoryModel CategoryModel { get; set; }
}
ListNews
to show list of news; and
NewsModel
for edit or insert.
Now I need to use automapper
. The code below gives me an error:
public PartialViewResult Edit(int id)
{
var model = new CategoryViewModel();
var cat = _CategoryService.CategoryByID(id);
Mapper.Initialize(cfg => cfg.CreateMap<Category, CategoryModel>());
model.CategoryModel = Mapper.Map<Category, CategoryModel>(cat);
var categorymodel = _CategoryService.GetAllCategory();
Mapper.Initialize(cfg => cfg.CreateMap<Category, IEnumerable<CategoryModel>>());
model.List = Mapper.Map<Category, IEnumerable<CategoryModel>>(categorymodel);
return PartialView(model);
}
How can I solve this problem?
Upvotes: 2
Views: 1280
Reputation: 236318
You don't need to create new map for collections if you have map for types of those collections. So remove this line:
Mapper.Initialize(cfg => cfg.CreateMap<Category, IEnumerable<CategoryModel>>());
Also you are trying to map single object to collection. You should map collection to collections instead:
// move next line to Application_Start
Mapper.Initialize(cfg => cfg.CreateMap<Category, CategoryModel>());
var model = new CategoryViewModel();
var category = _CategoryService.CategoryByID(id);
model.CategoryModel = Mapper.Map<CategoryModel>(category);
var categories = _CategoryService.GetAllCategory();
model.List = Mapper.Map<IEnumerable<CategoryModel>>(categories);
Further considerations:
Mapper.Map<TDestination>
instead of Mapper.Map<TSource,TDestination>
because type of source can be inferred from method argumentcat
instead of category
. And name categoryModel
is just misleading - this variable holds list of categories.Upvotes: 1