I post a viewmodel to my controller and I automap it to the entity object and I persist it with the entry() method changing the state of it depending if it is to add or update. I made sure that the objects wasn't null after I automap it, maybe I'm persisting it wrong. My problem is that the nested objects in the does not persist the changes.
public ActionResult saveUpdatePessoa(PessoaViewModel id)
{
if (ModelState.IsValid)
{
var pes = MvcApplication.Mapper.Map<PessoaViewModel, Pessoa>(id);
using (var db = new CityManagerDbCtx())
{
db.Entry(pes).State = pes.codigo == 0 ? EntityState.Added : EntityState.Modified;
//db.Entry(pes.endereco).State = pes.endereco.codigo == 0 ? EntityState.Added : EntityState.Modified;//Gives me error here if I uncomment this line
db.SaveChanges();
string smsg = id.codigo > 0 ? "Pessoa editada com sucesso." : "Pessoa salva com sucesso.";
ModelState.Clear();
return Json(new SubmitFormViewModel
{
success = true,
form = RenderHelper.PartialView(this, PESSOA_FORM_VIEW, new PessoaViewModel { dt_cad = DateTime.Now.Date, dt_nasc = DateTime.Now.Date }),
successMessages = new string[] { smsg },
errorMessages = new string[] { }
});
}
}
return Json(new SubmitFormViewModel
{
success = false,
form = RenderHelper.PartialView(this, PESSOA_FORM_VIEW, id),
successMessages = new string[] { },
errorMessages = ModelState.Values.SelectMany(m => m.Errors).Select(e => e.ErrorMessage).ToArray()
});
}