Updating data with entity framework

4

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

    
asked by anonymous 27.11.2014 / 17:57

4 answers

1

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();
    }
}
    
20.03.2016 / 19:55
1

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 });
    }
}
    
27.11.2014 / 19:05
1

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); 
    
26.01.2015 / 20:51
0

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();
}
    
09.02.2018 / 17:55