I have 2 models, Products
and Categories
, these are from the model on the repository:
IEnumerable<Product>
IEnumerable<Category>
I create a WebAPI and introduce AutoMapper eventually having code as below to return the products and categories in their own separate classes
public class ProductsController : ApiController
{
....
public IHttpActionResult Get()
{
try
{
IEnumerable<Product> products = GetProducts();
var mappedResult = _mapper.Map<IEnumerable<ProductModel>>(products);
return Ok(mappedResult);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
As i say same code in a new class for Category. Notice the new model for this class so its separate from the Domain model (ProductModel
).
I now would like to create a page in my MVC application (not .Net Core) which needs to display a list of categories in a dropdown and list the products with a foreach loop. I create a new class as below
Public Class ProductsAndCategoriesModel
{
public ProductModel Products { get; set; }
public CategoryModel Categories { get; set; }
}
The idea here is to have a new method to load the same products and categories data but in its own class. Im following the same convention as above but how do i map two different data sources to this one class using AutoMapper?
var mappedResultProducts = _mapper.Map<IEnumerable<ProductsAndCategoriesModel>>(products);
var mappedResultCategories = _mapper.Map<IEnumerable<ProductsAndCategoriesModel>>(cats);
//return Ok(mappedResult);
I need to map products to Products found in ProductsAndCategoriesModel and Categories found in ProductsAndCategoriesModel. I tried to pass in categories but couldnt as it threw a compiler exception. How could i achieve this?
Edit 1
public ProductCategoryProfile()
{
CreateMap<Product, ProductsAndCategoriesModel>();
CreateMap<Category, ProductsAndCategoriesModel>();
}
CodePudding user response:
No need to make things more complicated than they should be. Why don't you simply do it like this:
Model class:
public Class ProductsAndCategoriesModel
{
public IEnumerable<ProductModel> Products { get; set; }
public IEnumerable<CategoryModel> Categories { get; set; }
}
Mapping profile:
public ProductCategoryProfile()
{
CreateMap<Product, ProductModel>();
CreateMap<Category, CategoryModel>();
}
Controller:
public IHttpActionResult Get()
{
try
{
IEnumerable<Product> products = GetProducts();
IEnumerable<Category> categories = GetCategories();
var result = new ProductsAndCategoriesModel
{
Products = _mapper.Map<IEnumerable<ProductModel>>(products),
Categories = _mapper.Map<IEnumerable<CategoryModel>>(categories)
}
return Ok(result);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}