在FluentValidation中检查列表中的属性是唯一的

时间:2016-01-25 01:29:10

标签: c# .net fluentvalidation

我正在努力确保列表具有唯一的SSN。我得到的"属性名称无法自动确定表达式元素=>元件。请通过调用' WithName'"来指定自定义媒体资源名称。错误。我们能在这里知道我做错了吗?

    using FluentValidation;
    using FluentValidation.Validators;

    public class PersonsValidator : AbstractValidator<Persons>    
    {
        public PersonsValidator()
        {
            this.RuleFor(element => element)
               .SetValidator(new SSNNumbersInHouseHoldShouldBeUnique<Persons>())
.WithName("SSN");
                .WithMessage("SSN's in household should be unique");
        }
    }

    public class SSNNumbersInHouseHoldShouldBeUnique<T> : PropertyValidator
    {
        public SSNNumbersInHouseHoldShouldBeUnique()
        : base("SSN's in household should be unique")
        {
        }

        protected override bool IsValid(PropertyValidatorContext context)
        {
            var persons = context.Instance as Persons;
            try
            {
                if (persons == null)
                {
                    return false;
                }

                var persons = persons.Where(element => element.SSN.Trim().Length > 0);
                var allSSNs = persons.Select(element => element.SSN.Trim());
                if (allSSNs.Count() > allSSNs.Distinct().Count())
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }

    public class Persons : List<Person>
    {}

    public class Person
    {
        public string SSN{ get; set; }
    }

1 个答案:

答案 0 :(得分:2)

我使用的是FluentValidation版本4.6。根据Jeremy Skinner(FluentValidation的作者),我需要至少5.6才能使用模型级规则(如RuleFor(element =&gt; element))。 作为一种解决方法,我在实际的类本身上添加了此验证,而不是创建验证类。希望这有助于某人。

using FluentValidation;
using FluentValidation.Results;

 public class Persons : List<Person>
{
public void ValidateAndThrow()
        {
            var errors = new List<ValidationFailure>();
            try
            {
                var persons = this.Where(element => element.SSN.Trim().Length > 0);
                var allSSNs = persons.Select(element => element.SSN.Trim());
                if (allSSNs.Count() > allSSNs.Distinct().Count())
                {
                    var validationFailure = new ValidationFailure("UniqueSSNsInHouseHold", "SSN's in a household should be unique");
                    errors.Add(validationFailure);
                }         
            }
            catch (Exception ex)
            {
            }

            if (errors.Any())
            {
                throw new ValidationException(errors);
            }
        }
}