Is there Data Annotation that avoids duplication of data in the Bank?

5

How do I prevent data being duplicated in the database using Data Annotation or would it be through another validation?

    
asked by anonymous 10.11.2016 / 16:18

3 answers

4

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

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

No model:

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

UserController:

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

More here: link

    
10.11.2016 / 17:24
5
public class User
{       
   [Index(IsUnique=true)]
   public string UserName{get;set;}
}
    
10.11.2016 / 16:26
3

There are some ways, which is probably best for you would be to use the Index attribute to create an index in the database and indicate that it should have a unique key.

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

You can mount the index with multiple columns.

Do not forget to add the namespace System.ComponentModel.DataAnnotations.Schema to use this attribute.

Documentation .

    
10.11.2016 / 17:25