How do I prevent data being duplicated in the database using Data Annotation or would it be through another validation?
How do I prevent data being duplicated in the database using Data Annotation or would it be through another validation?
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
public class User
{
[Index(IsUnique=true)]
public string UserName{get;set;}
}
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.