0

对于ICustomValidate在 ASP.NET 样板中,我们可以验证字段的值。

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

比如新建学生时,我们会检查同名学生是否已经存在。我们可以把这个逻辑移到ICustomValidate?

4

1 回答 1

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 中进行自定义验证:

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));
        }
    }
}
于 2018-04-13T03:18:17.423 回答