检查ASP.NET Boilerplate的ICustomValidate中的现有记录

时间:2018-04-12 08:12:32

标签: c# validation asp.net-core custom-validators asp.net-boilerplate

对于ASP.NET Boilerplate中的ICustomValidate,我们可以验证该字段的值。

我想知道是否能够并建议在ICustomValidate中检查学生的已添加名称是否已存在。

例如,在创建新学生时,我们将检查是否已存在同名学生。我们可以将此逻辑移至ICustomValidate吗?

1 个答案:

答案 0 :(得分:1)

你可以:

public class CreateStudentDto : ICustomValidate
{
    public string Name { get; set; }

    public void AddValidationErrors(CustomValidationContext context)
    {
        using (var scope = context.IocResolver.CreateScope())
        {
            using (var uow = scope.Resolve<IUnitOfWorkManager>().Begin())
            {
                var studentRepository = scope.Resolve<IRepository<Student, long>>();

                var nameExists = studentRepository.GetAll()
                    .Where(s => s.Name == Name)
                    .Any();

                if (nameExists)
                {
                    var key = "A student with the same name already exists";
                    var errorMessage = context.Localize("sourceName", key);
                    var memberNames = new[] { nameof(Name) };
                    context.Results.Add(new ValidationResult(errorMessage, memberNames));
                }

                uow.Complete();
            }
        }
    }
}

但是这种验证通常在域管理器中完成,例如AbpUserManager

DTO中的

Custom Validation建议用于不变条件:

public class CreateTaskInput : ICustomValidate
{
    public int? AssignedPersonId { get; set; }

    public bool SendEmailToAssignedPerson { get; set; }

    public void AddValidationErrors(CustomValidatationContext context)
    {
        if (SendEmailToAssignedPerson && (!AssignedPersonId.HasValue || AssignedPersonId.Value <= 0))
        {
            var errorMessage = "AssignedPersonId must be set if SendEmailToAssignedPerson is true!";
            context.Results.Add(new ValidationResult(errorMessage));
        }
    }
}