Early this morning, a newbie MVC developer approached me for help to make the AutoMapper works.
Here's our simple work around:
Inside the Global.asax.cs,
Application Start()
{
.....
MyAutoMap();
}
public void MyAutoMap()
{
Mapper.Reset();
Mapper.CreateMap<DogViewModel, Dog>();
Mapper.CreateMap<Dog, DogViewModel>();
Mapper.AssertConfigurationIsValid();
}
But of course we make sure he had a ViewModel. He simply copied the Dog.cs (model) to Models folder and renamed it to DogViewModel.
In his test case, we replaced his model to
var model = new DogViewModel();
And in Controller, we modified his code to something like this
public ActionResult Create()
{
return View(new DogViewModel());
}
[HttpPost]
public ActionResult Create(DogViewModel viewDog)
{
if (ModelState.IsValid)
{
Dog dog = AutoMapper.Mapper.Map<DogViewModel, Dog>(viewDog);
_repo.CreateDog(dog);
_repo.SaveChanges();
return RedirectToAction("Index", "Animal");
}
return View();
}
No comments:
Post a Comment