error while saving or updating with EntityFramework

3

I have the following method:

using (var context = new ClassContexto(ClassMaster.conexao()))
{
    using (DbContextTransaction tran = context.Database.BeginTransaction(IsolationLevel.ReadCommitted))
    {
        try
        {
            pacienteModel.situacao = 1;
            pacienteModel.confirmado = 0;
            pacienteModel.dt_cadastro = DateTime.Now.ToString("yyyy/MM/dd");

            context.Set<PacienteModel>().Add(pacienteModel);
            tran.Commit();
            context.SaveChanges();
            retorno = "200";
        }
        catch (Exception erro)
        {                               
            if (erro.InnerException.InnerException.Message.ToLower().Contains("duplicate"))
            {                                    context.Entry(paciente).State = System.Data.Entity.EntityState.Modified;
                tran.Commit();
                context.SaveChanges();
                retorno = "200";
            }
            else
                retorno = erro.Message;
        }
    }
}

The problem is when it is an update, in the Try block an exception is raised because the record already exists, ok. In the catch block, it should update, but it generates the same exception, says that the record already exists, expected it to update normally. What is wrong there?

    
asked by anonymous 20.12.2017 / 13:07

3 answers

3

I do not see any reason for you to use BeginTransaction , you are trying to save a single object if something goes wrong with it so nothing will be changed in the database, there is no reason to use the transaction here. >

At this point I would use a simpler code.

public void Alterar(PacienteModel entidade)
{
    using (var context = new ClassContexto(ClassMaster.conexao()))
    {
        if (entidade.ID == 0)
            context.Set<PacienteModel>().Add(entidade);
        else
        {
            context.Set<PacienteModel>().Attach(entidade);  
            context.Entry(entidade).State = EntityState.Modified;
        }
        context.SaveChanges();
    }
}
    
20.12.2017 / 13:50
2

I believe that before taking the action you need to make sure it is an inclusion or update. This way you can set the status of the action as follows:

    context.Entry(PacienteModel).State = pacienteModel.Id == 0 ? /*ou outra chave que você tenha de referência */
        EntityState.Added : EntityState.Modified;    
    //e então...
    context.SaveChanges();

Here's a good reference: link

Hope it helps.

    
20.12.2017 / 13:48
0

It seems to me that you are facing a scope problem and I would not recommend you to use the try / catch structure for this either ... but this will solve your problem

using (var context = new ClassContexto(ClassMaster.conexao()))
{
      using (DbContextTransaction tran = context.Database.BeginTransaction(IsolationLevel.ReadCommitted))
      {
              pacienteModel.situacao = 1;
              pacienteModel.confirmado = 0;
              pacienteModel.dt_cadastro = DateTime.Now.ToString("yyyy/MM/dd");


          try
          {
              context.Set<PacienteModel>().Add(pacienteModel);
              tran.Commit();
              context.SaveChanges();
              retorno = "200";
          }
          catch (Exception erro)
          {                               
              if (erro.InnerException.InnerException.Message.ToLower().Contains("duplicate"))
              {                                    
                  context.Entry(paciente).State = System.Data.Entity.EntityState.Modified;
                  tran.Commit();
                  context.SaveChanges();
                  retorno = "200";
              }
              else
                  retorno = erro.Message;
          }
      }
  }
    
20.12.2017 / 13:10