Preventing duplication of data

Asked

Viewed 229 times

1

I want to prevent a criminal record of a person whose social security number is already registered. I tried to do something but it gives an error, because I set the CPF field as Constraint. Instead of giving the error I would like to be shown a message warning that the CPF is already registered.

Makes that mistake:

exceção

  • What are you using? Winforms, WPF, Asp.net MVC? How are you trying to insert? You are using Entity Framework?

1 answer

5


This is what is expected and is correct behavior. All that remains is to decide what to do when the error occurs.

Put the code snippet that does the operation in a try-catch and define what to do when the error happens.

Everything on the block try will be "protected". So when the exception occurs it can be captured in the catch and in this block you can do what you want.

Since the question doesn’t have a code I’ll put something generic here:

try {
    MetodoQueTentaFazerUmCadastro();
    TudoDeuCerto(); //se der a exceção no método anterior nem executará isto
} catch (OracleException ex) when (ex.ErrorCode == 1) { //C# 6
    WriteLine("Este CPF já está cadastrando entre os funcionários");
}

I put in the Github for future reference.

If you are not using C# 6, or higher, then you have to transform this when in a if inside the block of catch. It’s not ideal, but it will work.

try {
    MetodoQueTentaFazerUmCadastro();
    TudoDeuCerto(); //se der a exceção no método anterior nem executará isto
} catch (OracleException ex) {
    if (ex.ErrorCode == 1) {
        WriteLine("Este CPF já está cadastrando entre os funcionários");
    } //pode ser que queira usar um else para outros casos
}

Documentation.

Be careful not to abuse this resource, many people do it. It would be good to understand its use completely before getting used elsewhere.

Browser other questions tagged

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