3
Good afternoon, I have the following Entity class marked by Data Annotations:
public class Cargo
{
[Key]
[Display(Name ="Código")]
public int Codigo { get; set; }
[Required(AllowEmptyStrings =false, ErrorMessage = "A descrição do cargo é obrigatória")]
[Display(Name = "Descrição")]
public string Descricao { get; set; }
[Display(Name = "Ativo")]
public bool Ativo { get; set; }
}
I have the following method that captures class errors:
public static IEnumerable<ValidationResult> getErrosValidacao(object objeto)
{
List<ValidationResult> resultadoValidacao = new List<ValidationResult>();
var contexto = new ValidationContext(objeto, null, null);
Validator.TryValidateObject(objeto, contexto, resultadoValidacao, true);
return resultadoValidacao;
}
Finally I have the following method that validates the Insert at the bank:
public void ValidarInsercao(Cargo cargo)
{
if (string.IsNullOrWhiteSpace(cargo.Descricao))
{
throw new ArgumentNullException("A descrição do cargo não tem um valor válido.");
}
objCargo.Inserir(cargo);//tenta inserir no banco de dados
}
I’d like to validate the object office by the rules of Dataannotations and if there were any mistakes he’d make an exception, how can I do that?
I will try to implement here friend as soon as I can mark as resolved!
– lima_t
Friend your class worked perfectly and could not be better, thank you very much!
– lima_t