Kianoush
Kianoush

Reputation: 47

cannot convert from 'System.Collections.Generic.IEnumerable<x>' to 'x' when using automapper

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

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

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:

  • Use Mapper.Map<TDestination> instead of Mapper.Map<TSource,TDestination> because type of source can be inferred from method argument
  • Use meaningful names of variables. There is no need to save few characters to use cat instead of category. And name categoryModel is just misleading - this variable holds list of categories.
  • And last - don't create maps each time you want to map objects. Create maps once on application start.

Upvotes: 1

Related Questions