Updating data with Entity framework

Asked

Viewed 1,989 times

4

In the project I’m developing, MVC5, Entity 6, I’m simply not being able to update the data.

The Code:

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

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

Data is saved normal with:

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

But the update does not occur. = T

  • Put the code to all your action Edit to make it clearer ?

  • That’s the whole code.

  • This existing database was created by the application?

  • No. Old bank.

  • Solved the problem?

  • I already had this error, I concerted doing the following: First I search the bank who I want to edit : var Client = 'context.entidade.firstOrDefault(x=> x.Id == Iddocliente); Ai start editing: Client.name = client.name. , and so I give the context.Savechanges()

Show 1 more comment

4 answers

1

Three alternatives. Use specific version instead of Object:

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

Go straight to ChangeTracker make the change:

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

Or, if it is a particular code snippet, and you are already tired of the somewhat mysterious EF errors, 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();

For documentation, DbContext.Entry(object) should be a valid way to access the properties of a tracked or attached object, and change State to Modified would be all necessary to force the data UPDATE. But from time to time does not scroll, simply.

The generic version, if you want to update 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();
    }
}

1

I’ll do it like this, see if it helps you.

[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 });
    }
}
  • 1

    If you used the Find to get the registration in the Bank and in no time saw you set AutoDetectChangesEnabled to false, I believe that the context itself is already monitoring this entity, so modifying its State manually is unnecessary.

1

Place your code inside a Modelstate and add break point in 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); 
  • I don’t think this answers the question, as a invalidated Model would make Savechanges raise an exception of the type DbValidationError and I believe this he would have detected.

  • @Tobymosque as it did not add a possible error, I added only to help debug, to check if it is sending a valid template to be edited. I waited for the answer of the author to be able to elaborate an answer to the problem. I did not post in the comment, because I thought it would be a little "cramped" for understanding.

  • I also think it’s strange that you’re not saving, I believe the problem is not in this block of code, but in modeling.

  • @Tobymosque I had a very similar problem once. In this case Edit (which requires an id) was not receiving the ID, not leaving the model valid, therefore not saving. But as the author did not manifest himself, he must have found the solution.

0

You should first check if your entity ID is filled and then you could try this way doing a treatment in the object state, where Dbbase is your context and Tentity your 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();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.