I have one base class and 3 sub classes and single viemodel with all properties. I want in my controller create action to bind this viewmodel to concrete sub type.
Here is my create action which doesn't work (I'm getting Error mapping types):
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(AdViewModel vm)
{
if (ModelState.IsValid)
{
var ad = Mapper.Map<Ad>(vm);
_context.Ads.Add(ad);
_context.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
This is automapper configuration:
Mapper.Initialize(config =>
{
config.CreateMap<AdViewModel, Ad>().ReverseMap();
config.CreateMap<AdViewModel, Realty>().ReverseMap();
config.CreateMap<AdViewModel, Auto>().ReverseMap();
config.CreateMap<AdViewModel, Service>().ReverseMap();
});
And this is working code, but I doubt to use it:
public IActionResult Create(AdViewModel vm)
{
if (ModelState.IsValid)
{
if (vm.RealtyType != null)
{
var ad = Mapper.Map<Realty>(vm);
_context.Add(ad);
}
else if (vm.AutoType != null)
{
var ad = Mapper.Map<Auto>(vm);
_context.Add(ad);
}
else
{
var ad = Mapper.Map<Service>(vm);
_context.Add(ad);
}
_context.SaveChanges();
return RedirectToAction("Index");
}
return View();
}