Updating data with entity framework

Posted on

Question :

In the project I’m developing, MVC5, Entity 6, I just can not seem to update the data.

The Code:

zyon.TB_Cliente.Attach(cliente);
zyon.Entry(cliente).State = System.Data.Entity.EntityState.Modified;
zyon.SaveChanges();

That works when I create the database through the project, it is not working when I connect to an existing database.

The data is saved normal with:

zyon.TB_Cliente.Add(cliente);
zyon.SaveChanges();

But the update does not occur. = T

    

Answer :

Three alternatives. Use the specific version instead of the object:

zyon.Entry<TB_Cliente>( client ).State = System.Data.Entity.EntityState.Modified;

Go straight on ChangeTracker make the change:

zyon.ChangeTracker.Entries<TB_Cliente>().First( x => x.Entity == client ).State = System.Data.Entity.EntityState.Modified;

Or, if it’s a particular code snippet, and you’re already tired of the somewhat mysterious errors of EF, do both:

zyon.TB_Cliente.Attach( client );
zyon.Entry( client ).State = System.Data.Entity.EntityState.Modified;
zyon.ChangeTracker.Entries<TB_Cliente>().First( x => x.Entity == client ).State = System.Data.Entity.EntityState.Modified;
zyon.SaveChanges();

By documentation , DbContext.Entry(object) should be a valid way to access the properties of a crawled or attached object, and changing the State to Modified would be all that is required to force the UPDATE of the data. But every now and then it does not just roll.

The generic version, if you want to do UPDATE on several objects in an immediate way (and outside the official transaction!):

public void DetachedUpdate(T obj)
{
    using (var context = new Context())
    {
        context.Set<T>().Attach(obj);
        context.ChangeTracker.Entries<T>().First(e => e.Entity == obj).State = EntityState.Modified;
        context.SaveChanges();
    }
}

    

I’ll do it, see if it helps.

[Authorize]
[HttpPost]
[ControleDeAcesso(TipoAcao.Normal)]
public ActionResult Detalhar(string btnSubmit, Memo model)
{
    // Verifica se o modelo é válido, senão retorna para a View
    if (!ModelState.IsValid)
        return View(model);

    using (var db = new ERPContext()) // Cria o contexto de conexão
    {
        var memo = db.Memo.Find(model.MemoID); // Busco o registro
        var retorno = FlexGestor.Helpers.EntidadeBaseExt.ValidarRegistro(memo, TipoAcao.Gravar); // Valido o registro
        if (retorno != "")
        {
            TempData["MsgRetornoError"] = retorno;
            return RedirectToAction("Index", "Home");
        }

        if (btnSubmit != "Excluir")
            UpdateModel(memo);  // Se não for exclusão, pego os dados do model e jogo no registro buscado
        Helpers.EntidadeBaseExt.AtribuirValores(memo, btnSubmit); // Função interna minha
        db.Entry(memo).State = EntityState.Modified; // Seto como modificado 
        db.SaveChanges(); // Salvo

        // Retorno para a view conforme ação original
        if (btnSubmit == "Excluir")
            return RedirectToAction("Index", controller);

        return RedirectToAction("Detalhar", controller, new { id = model.MemoID });
    }
}

    

Place your code inside a ModelState and add break point to the method to see if there is an error with the edited data.

It would look something like this:

     if (ModelState.IsValid)
    {
       zyon.TB_Cliente.Attach(cliente);
       zyon.Entry(cliente).State = System.Data.Entity.EntityState.Modified;
       zyon.SaveChanges();
    }
    return View(cliente); 

    

You should first verify that your entity ID is filled and then try this way by doing a treatment on the state of the object, where DbBase is its context and TEntity its entity in the client case.

public void Atualiza(TEntity entidadeEntity)
{
    if (DbBase.Entry(entidadeEntity).State == EntityState.Detached)
        DbBase.Set<TEntity>().Attach(entidadeEntity);

    DbBase.Entry(entidadeEntity).State = EntityState.Modified;
    DbBase.SaveChanges();
}

    

Leave a Reply

Your email address will not be published. Required fields are marked *