Better Method Using Validator.TryValidateObject(..) with a List

时间:2019-01-09 22:11:06

标签: c# validation asp.net-core .net-core

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();
    }

0 个答案:

没有答案