Navigations properties are not updating

61 Views Asked by At

For some reason my edit action are not updating my navigations properties Check de codes

 public ActionResult Edit(ClienteViewModel clienteViewModel)
    {
        if (ModelState.IsValid)
        {
            var cliente = Mapper.Map<Clientes>(clienteViewModel);
            _context.Entry(cliente).State = EntityState.Modified;
            _unitOfWork.Commit();
            return RedirectToAction("Index");
        }
        return View(clienteViewModel);
    }

enter image description here

Any ideas?

EDIT I added a hidden field with endereco.id on edit view and now Endereco.Id is going to controller, but the error still the same

enter image description here

1

There are 1 best solutions below

2
CodeNotFound On BEST ANSWER

If you look at the primary key Id of your navigational property Endereco you will see that its value is Guid.Empty 00000000-0000-0000-0000-000000000000.

So updating that entity will generate a SQL query with this WHERE clause below:

WHERE Id = '00000000-0000-0000-0000-000000000000'

Of course a line with that empty guid doesn't exist into your table.

Your original code do a mapping with AutoMapper so make sure that all properties are mapped correctly when calling the line below:

var cliente = Mapper.Map<Clientes>(clienteViewModel);

Updates: Based on your comment you also need to be sure that the navigational property state is changed to EntityState.Modified (because changing the root entity's state doesn't impact the navigational properties) like below:

_context.Entry(cliente.Endereco).State = EntityState.Modified;