Search code examples
c#databaseentity

Updating table with entity does not work


I'm trying to update a table using entity. The new data is getting inside usu_login and usu_senha, but when the code get's to SaveChanges(); bit it doesn't really work. Am I missing something? Why does the update doesn't occour? I tried inserting a new user with the new data and that actually works, just the update is giving me a hard time.

[Authorize]
    [HttpPost]
    public string AtualizarCredenciais(string usu_senha, string usu_login)
    {
        try
        {
            //Busca o usuário com o ID de sessão.
            USUARIOS usuario = mUsuario.BuscarUsuario(int.Parse(HttpContext.User.Identity.Name));

            //Cria uma instância de contexto do banco.
            BdContext dbcontext = new BdContext();

            //Mudança de senha e usuário pro novo usuário.
            usuario.USU_LOGIN = usu_login;
            usuario.USU_SENHA = usu_senha;

            dbcontext.SaveChanges();

            return "Credenciais atualizadas.";
        }
        catch (Exception e)
        {
            Debug.WriteLine(e.ToString());
            return "Erro na atualização de credenciais.";
        }
    }

EDIT: the mUsuario.BuscarUsuario method is used to return from the database an object of the Usuario type with all it's values loaded using the identity name of the user that's currently in session.

SOLVED: David answer was correct, what I did was to bring the buscarUsuario method to inside the dbcontext. This was the code for the BuscarUsuario:

public USUARIOS BuscarUsuario(int id)
    {
        try
        {
            db = new BdContext();
            USUARIOS usuario = db.USUARIOS.Find(id);
            db.Dispose();
            return usuario;
        }
        catch(Exception ex)
        {
            throw ex;
        }
    }

So instead of using it just to encapsulate an object I used the .Find method to bring me an 'usuario' in the dbcontext:

USUARIOS usuario = dbcontext.USUARIOS.Find(int.Parse(HttpContext.User.Identity.Name));

Solution

  • What is mUsuario.BuscarUsuario()? It doesn't seem to be related to your data context in any way. Essentially what you're doing is instantiating a data context, not using anything in it, and then saving. So, as far as the data context is concerned, there are no changes to save.

    Not being familiar with the native language in this code (Portuguese?), I'm going to use placeholder names. But essentially what you need is to get the model from the data context. Something like:

    BdContext dbcontext = new BdContext();
    
    USUARIOS usuario = dbcontext.SomeListOfEntities.Single(u => u.SomeID == int.Parse(HttpContext.User.Identity.Name));
    
    // make changes to the "usario" object
    
    dbcontext.SaveChanges();
    

    Presumably mUsuario looks to be an attempt to encapsulate database operations in a helper object/method/etc. of some sort. But what seems to be happening is that the encapsulation is also encapsulating the data context itself. If you want to keep using that object, then that object is going to have to in some way expose the operation to call .SaveChanges() on its data context.

    Basically, two different data contexts don't know about each other's objects.