Make a select in the database and prohibit the insertion of repeated C# SQL Server data

Asked

Viewed 159 times

0

I am new to C# and SQL Server, I need help to build something that for you is simple for sure. In my database has id, name and CPF. The Key is the ID and it goes automatically, but I also didn’t want to let the number repeat itself. how to build a private bool by making a select in the database prohibiting the insertion of repeated data? Parlance: C# BD: Sqlserver

  • 1

    Creating a UNIQUE constraint in the CPF field is not enough?

  • No no, if you create a Unique the system in C# returns nothing

  • ??? How to return? A UNIQUE constraint will not allow a record with the same existing CPF to be included in another table record.

1 answer

0

You can do it 2 ways.

  1. When creating the table, Voce can mark the CPF field as Unique. This way, the validation will be on the side of the database.

  2. Before registering in the bank, Voce can make a query and check if the CPF already exists in the bank. If it does not exist, you save the record. If it exists, you do not save and treat the message.

  • Right, but how do I do it in C#? Because I will put as Unique in the database, when trying to insert will give error.

  • @Wanderfrança, this article shows an example of how it can be done. https://www.c-sharpcorner.com/UploadFile/219d4d/how-to-check-if-the-username-is-unique-or-not-in-mvc-5/ Basically it puts Dataannotation [Remote("[NOME_DO_SEU_METODO_DE_VALIDACAO]","[NOME_DO_SEU_CONTROLLER]",ErrorMessage="[MENSAGEM_DE_VALIDAÇÂO]")] in the attribute, in your case it would be the CPF attribute. Then, use the following method to perform the validation. public Jsonresult Isuserexists(string Cpf) ː Return Json(!db.Users.Any(x => x.CPF== Cpf) ,Jsonrequestbehavior.Allowget); }

Browser other questions tagged

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