Cześć. Mam takie problem. Chciałbym dodać możliwość dodania produktu tylko mam taki problem. Nie wiem czemu ale wyskakuje mi błąd kiedy mapuje z ViewModel na DTO wiecie może dlaczego tak się dzieje ?
namespace Shop.Application.AutoMapper
{
public static class AutoMapperConfig
{
public static IMapper Initialize()
=> new MapperConfiguration(cfg =>
{
cfg.CreateMap<Shop.Core.Domain.Product, ProductDTO>().ForMember(x => x.Category, m => m.MapFrom(x => x.CategoryName()));
cfg.CreateMap<Shop.Core.Domain.Product, CreateProductDTO>();
cfg.CreateMap<Shop.Core.Domain.Category, CategoryDTO>();
cfg.CreateMap<Shop.Core.Domain.Category, ListCategoryDTO>();
cfg.CreateMap<ListProductDTO, HomeProductViewModel>();
cfg.CreateMap<ListCategoryDTO, HomeCategoryViewModel>();
cfg.CreateMap<Shop.Core.Domain.Product, ListProductDTO>().ForMember(x => x.Category, m => m.MapFrom(x => x.CategoryName()));
cfg.CreateMap<ProductDTO, ProductDetailViewModel>();
cfg.CreateMap<CreateProductDTO, CreateProductViewModel>();
}).CreateMapper();
}
}
public class CreateProductDTO
{
public Guid Id { get; set; }
public Guid CategoryId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
public class CreateProductViewModel
{
public Guid Id { get; set; }
public Guid CategoryId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
[HttpGet]
public async Task<ViewResult> AddProduct()
{
CreateProductViewModel model = new CreateProductViewModel();
model.Categories = categoryService.GetAll().Result.Select(x => new SelectListItem() { Text = x.Name, Value = x.Id.ToString()});
return View(model);
}
[HttpPost]
public async Task<ActionResult> AddProduct(CreateProductViewModel model)
{
var product = mapper.Map<CreateProductDTO>(model);
await productService.AddProduct(product);
return RedirectToAction("Index", "Home");
}
A sam błąd wygląda tak: