Is there a Data Annotation that prevents data duplication in the Database?

Asked

Viewed 1,227 times

6

How do I prevent data from being duplicated in the database using Data Annotation or via another validation?

  • You want to create a Unique Key via data Annotation, right?

  • yes, for example, single email, single product etc...

  • Eduardo’s answer already resolves.

  • Okay, thanks for the help

  • @Fabiosouza Using EF? Which version?

  • @bigown excuse ignorance, but what would EF? Entity Framework? if it is is version 6

  • @Fabiosouza, answering your question above, EF, and abbreviation for Entity Framework.

Show 2 more comments

3 answers

5

public class User
{       
   [Index(IsUnique=true)]
   public string UserName{get;set;}
}
  • with this he already checks in the bank if he already has the information registered?

  • [Index(..)] is not recognized by the system, give me this message: the type or namespace name 'Index' could not be found (are you Missing a using Directive or an Assembly Reference?) and if I click CTRL+point he asks to generate a class...

  • with this it will create a field that will not be able to have equal values. if you want to check will have to customize your date.

4


One way to do this is with RemoteValidation, works like this: you should create a ActionResult return a JsonResult with true or false indicating whether the validation has passed. This validation will be done by Ajax if using Unobtrusive Validation.

This is not a type of validation that will create an index in the database, which would make an exception when trying to save duplicate data. The index guarantees you integrity, for sure, but this solution is more user-friendly and it is not necessary to treat the exception flow. Use both solutions if applicable.

In the model:

// primeiro parametro é nome da ação, o segundo do controller
[Remote("ValidarEmailUnico", "Usuario", ErrorMessage = "E-mail já cadastrado")]
public string Email{ get; set; }

User controller:

 public ActionResult ValidarEmailUnico(string Email)
 {
    var emailDisponivel = contexto.Usuarios.Where(u => u.Email == Email).Count() == 0;
    return Json(emailDisponivel, JsonRequestBehavior.AllowGet);
 }

More here: http://www.macoratti.net/15/02/aspn_vremt1.htm

  • var emailDisponivel = contexto.Usuarios.Any(u => u.Email == Email); So get better and more performative.

  • 1

    In case would have to reverse the return, because Any will return true if there is e-mail registered.

  • this, this way is better, but it would still have to pass the key parameter of the table ...

3

There are some forms, the one that is probably the most suitable for you would be to use the attribute Index to create an index in the database and indicate that it must have a unique key.

public class SuaClasse {       
   [Index("NomeDoIndice", IsUnique = true)]
   public string ColunaUnica { get; set; }
}

I put in the Github for future reference.

It is possible to mount the index with multiple columns.

Don’t forget to add the namespace System.ComponentModel.DataAnnotations.Schema to use this attribute.

Documentation.

  • what would be the "Nomedoindice"?

  • It would be the name you want to give to the index within the database. It has to have a name. It’s like you’re writing it into the database. It’s like wearing a CREATE TABLE.

  • Um maybe that’s why he was making a mistake running my system saying that my table already existed... you know what I could be doing wrong ? I tried with the same name as the field, different name and even no name, but always gave the same msg.

  • There the problem seems to be another completely different from what is in the question.

  • This error only appears if using this Annotation

  • Then I edit the question showing what I did and the error that gives.

  • Yeah, that’s normal, if you take something that’s making a mistake it doesn’t really show up, but it’s not what you want. You should not edit the question, if you have another problem, it should be another question. This seems to have been solved. See [tour].

Show 2 more comments

Browser other questions tagged

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