error saving or updating with Entityframework

Asked

Viewed 436 times

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 generated, because the record already exists, ok. In the catch block, you should update, but it generates the same exception, says that the record already exists, expected it to update normally. What is wrong there ?

  • your context.Savechanges(); shouldn’t be before your Tran. Commit();

3 answers

3


I don’t see any reason for you to use the BeginTransaction, you are trying to save a single object if something wrong happens to it then nothing will be changed in the bank, there is a reason to use the transaction here.

In that senario 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();
    }
}

2

I believe that before performing the action you need to make sure it is an inclusion or update. This way you can set the action state 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 a good reference: https://msdn.microsoft.com/en-us/library/jj592676(v=vs.113). aspx

I hope it helps.

0

It seems to me that you are facing a scope problem and I wouldn’t recommend you using the Try/catch structure for that 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;
          }
      }
  }
  • Leandro, what would you recommend?

  • 1

    You can check if the non-registration already exists or if your [id] is 0 and decide whether to add it to the connected or just update.

Browser other questions tagged

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