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?