How to handle duplicate key error?

Asked

Viewed 1,373 times

8

How do I handle duplicate key error? I need to display message to the user that the "Item is already registered"

Something like that:

try{

  //tenta inserir no Banco de Dados
  context.Produto.Add(_produto);
  context.SaveChanges();

}catch(exceção 1){

  //tratar erro de chave duplicada

}catch(exceção 2){

  // tratar erro diferente de chave duplicada

} 

Error always returns in class catch(Exception ex)

        _repositorio.ProdutoEstoque.Add(_produtoEstoque);
        _repositorio.SaveChanges();
    }
    catch (UpdateException ex)
    {
        SqlException innerException = ex.InnerException as SqlException;
        if (innerException != null && innerException.Number == 2627){                    
            //tratar erro de chave duplicada
            //o jeito que vai informar a view depende do resto da sua aplicação
            string msg = string.Empty;
            msg ="ERRO";
        }else
        {
            throw;
        }
    }
    catch (SqlException ex){
        if (ex.Number == 2627){
            string msg = string.Empty;
            msg = "ERRO";
        }else
        {
            throw;
        }
    }
    catch (Exception ex){  
         throw;               
    }
}

Print error

Erro apresentado

  • How about doing a query first? If you are saving records in multiple tables at the same time, you may not know where such duplication exists.

1 answer

7


I think this is what you need.

try {
    context.Produto.Add(_produto);
    context.SaveChanges();
} catch (UpdateException ex) {
    SqlException innerException = ex.InnerException as SqlException;
    if (innerException != null && innerException.Number == 2627) {
        //tratar erro de chave duplicada
        //o jeito que vai informar a view depende do resto da sua aplicação
    } else {
        throw;
    }
} catch(exceção 2) {
    // tratar erro diferente de chave duplicada
}

By the issue of the question still has one more level of exception DBUpdateException. Then you have to capture her first.

If you are using C# 6 you can improve:

try {
    context.Produto.Add(_produto);
    context.SaveChanges();
} catch (UpdateException ex) when (innerException?.Number == 2627) {
    //tratar erro de chave duplicada
} catch(exceção 2) {
    // tratar erro diferente de chave duplicada
}

I put in the Github for future reference.

If the second exception is Exception probably is better not capture there.

  • Got it... that . Number == 2627 would be the error code for Duplicate Key, I will test and then check the answer. Thank you!

  • This. See if you can fix what you want.

  • bigown didn’t work, I tested it and I realized that I always fall in Exception and not in Updateexception, I put an error print in the question and the most relevant code snippet.

  • This can’t see everything. Tell me if you have any more InnerException inside the image. I have seen that I had to capture the DBUpdateException before the UpdateException but there must be more.

  • That’s right there’s one more InnerException to DbUpdateException I captured her and only had to add: SqlException innerException = ex.InnerException.InnerException as SqlException;

Browser other questions tagged

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