I'd like to check my understanding and usage of the AutoMapper in my ASP.Net MVC app.
I setup the maps in Application_Start:
Mapper.CreateMap<Customer, CustomerViewModel>();
Mapper.CreateMap<CustomerViewModel, Customer>();
Mapper.AssertConfigurationIsValid();
To return a list of users associated with the logged in user, in my Customer Controller I have:
//
// GET: /Customer/
public ActionResult Index()
{
var customer = db.Customers.Where(x => x.UserName == User.Identity.Name).ToList();
IList<CustomerViewModel> customerVM = Mapper.Map<IList<Customer>, IList<CustomerViewModel>>(customer);
return View(customerVM);
}
To Edit a specific customers details I am using:
//
// GET: /Customer/EditPartial
public ActionResult EditPartial(int id)
{
var customer = db.Customers.Where(x => x.UserName == User.Identity.Name && x.CustomerId == id).FirstOrDefault();
CustomerViewModel customerVM = Mapper.Map<Customer, CustomerViewModel>(customer);
return PartialView(customerVM);
}
Where I Post back updates after making changes in the EditPartial view:
//
// POST: /Customer/EditPartial
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditPartial(CustomerViewModel customerVM)
{
if (ModelState.IsValid)
{
Customer customer = db.Customers.Where(x => x.UserName == User.Identity.Name && x.CustomerId == customerVM.CustomerId).FirstOrDefault();
if (customer == null)
{
return HttpNotFound();
}
customer.CustomerName = customerVM.CustomerName;
// How do I use AutoMapper here, instead of updating the domain model directly
customer.Email = customerVM.Email;
db.Entry(customer).State = EntityState.Modified;
db.SaveChanges();
/////////////////
// Now I want to return a customer list again
// Is this the best way to do it again
var customer2 = db.Customers.Where(x => x.UserName == User.Identity.Name).ToList();
IList<CustomerViewModel> customerVM2 = Mapper.Map<IList<Customer>, IList<CustomerViewModel>>(customer2);
return PartialView("CustomerListPartial", customerVM2);
}
this.Response.StatusCode = 400;
return PartialView("EditPartial", customerVM);
}
The code above works, I'm just not sure about using AutoMapper in the Post, and if my way of returning a partial list of customers is the best method.