1
[HttpPost]
public ActionResult _EditCustomer(CustomerViewModel CustomerViewModel)
{
    if (ModelState.IsValid)
    {
        try
        {
            Customers customer = entity.Customers.FirstOrDefault(x => x.sno == CustomerViewModel.sno);
            customer = AutoMapper.Mapper.Map<CustomerViewModel, Customers>(CustomerViewModel);
            entity.SaveChanges();

            return Content("<div class=\"success\">Müşteri düzenleme işlemi başarılı.</div>", "text/html");
        }
        catch (Exception e)
        {
            ModelState.AddModelError("", "Müşteri güncelleme hatası.");
        }
    }

    //Updating customer is failed!
    CustomerViewModel.Cities = entity.Cities;
    CustomerViewModel.PowerSuppliers = entity.PowerSuppliers;
    CustomerViewModel.Sectors = entity.Sectors;

    return PartialView(CustomerViewModel);
}

I debugged the code, and then in runtime customer is updating(automapper is working, I can see the changes), but entity.SaveChanges(); is not working.

Is there any another way to update records, when using automapper?

Thanks in advance.

AliRıza Adıyahşi
  • 15,658
  • 24
  • 115
  • 197

1 Answers1

1

Your code creates new customer entity, which is not attached to context:

var newCustomer = Mapper.Map<CustomerViewModel, Customers>(CustomerViewModel);

To update existing entity, use following Map method of automapper:

Mapper.Map(CustomerViewModel, customer);
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459