Preventing duplicate data

1

I want to prevent the registration of a person whose CPF has already been registered. I tried to do something but it was an error because I defined the CPF field as constraint . Instead of giving the error I would like to be shown a message advising that the CPF is already registered.

Give this error:

    
asked by anonymous 19.07.2016 / 22:17

1 answer

3

This is what is expected and is a correct behavior. You just have to decide what to do when the error occurs.

Put the snippet of code that does the operation into a try-catch and set what to do when the error occurs.

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

As the question does not have a code I'm going to go for 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");
}

If you are not using C # 6 or higher, you will have to convert that when to if into the catch block. 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 feature, many people do. #.

    
19.07.2016 / 22:31