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

Check for existing record in ICustomValidate of ASP.NET Boilerplate

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

我想知道在 ICustomValidate.

中是否可以并建议检查学生添加的名称是否已经存在

比如新建一个学生,我们会检查是否已经存在同名学生。我们可以将此逻辑移动到 ICustomValidate 吗?

您可以:

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

Custom Validation 在 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));
        }
    }
}