My objective is to determine if there is a better method to use TryValidateObject(..) with a list. Right now, I'm iterating through a list of items and using the TryValidateObject(..) method to validate. Does the Validator class offer any methods to accomplish this without iterating through each item?
For reuse, I created a utility class called 'DataAnnotationsValidator' to perform the TryValidateObject functions.
DataAnnotationsValidator.cs
public class DataAnnotationsValidator
{
public static bool TryValidate(object @object, out ICollection<ValidationResult> results)
{
var context = new ValidationContext(@object, serviceProvider: null, items: null);
results = new List<ValidationResult>();
return Validator.TryValidateObject(@object, context, results, validateAllProperties: true);
}
}
Repository.cs
public IQueryable<TEntity> GetAll()
{
IQueryable<TEntity> list = _db.Set<TEntity>().AsNoTracking();
foreach (TEntity entity in list)
{
if (!DataAnnotationsValidator.TryValidate(entity, out ICollection<ValidationResult> results))
{
foreach (ValidationResult item in results)
{
throw new Exception("Error: " + item.MemberNames.FirstOrDefault().ToString() + " - " + item.ErrorMessage);
}
}
}
return _db.Set<TEntity>().AsNoTracking();
}