对于ASP.NET Boilerplate中的ICustomValidate
,我们可以验证该字段的值。
我想知道是否能够并建议在ICustomValidate
中检查学生的已添加名称是否已存在。
例如,在创建新学生时,我们将检查是否已存在同名学生。我们可以将此逻辑移至ICustomValidate
吗?
答案 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
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));
}
}
}