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);
}

我调试了代码,然后在运行时客户正在更新(自动映射器正在工作,我可以看到更改),但entity.SaveChanges();没有工作。

使用自动映射器时,还有其他方法可以更新记录吗?

提前致谢。

4

1 回答 1

1

您的代码创建了新的客户实体,该实体未附加到上下文:

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

要更新现有实体,请使用以下Map自动映射器方法:

Mapper.Map(CustomerViewModel, customer);
于 2012-11-27T09:04:59.307 回答