我有以下“费用”实体的验证类:
public class ExpenseBaseValidator : AbstractValidator<Expense>
{
public ExpenseBaseValidator()
{
RuleFor(x => x.Description).NotEmpty();
RuleFor(x => x.Amount).NotNull();
RuleFor(x => x.BusinessID).NotEqual(0).WithMessage("BusinessID is required.");
RuleFor(x => x.ExpenseTypeID).NotEqual(0).WithMessage("ExpenseTypeID is required.");
RuleFor(x => x.CreatedDate).NotNull();
RuleFor(x => x.Transaction).SetValidator(new TransactionValidator());
}
}
然后我有 Transaction 的验证类,这是上面 Expense 类中的一个复杂属性:
public class TransactionBaseValidator : AbstractValidator<Transaction>
{
public TransactionBaseValidator()
{
RuleFor(x => x.BankAccountID).NotEqual(0).WithMessage("BankAccountID is required.");
RuleFor(x => x.EmployeeID).NotEqual(0).WithMessage("EmployeeID is required.");
RuleFor(x => x.TransactionDate).NotNull();
RuleFor(x => x.IsWithdrawal).NotNull();
RuleFor(x => x.Amount).NotNull();
RuleFor(x => x.Description).NotEmpty();
RuleFor(x => x.PaymentMethod).NotEmpty();
RuleFor(x => x.PaymentMethod).Length(0, 50).WithMessage("PaymentMethod can not exceed 50 characters");
}
}
现在这些是基类,我分别使用以下子类调用验证器:
public class ExpenseValidator : ExpenseBaseValidator
{
public ExpenseValidator()
: base()
{
RuleFor(x => x.Transaction)
.NotNull()
.When(x => x.IsPaid == true)
.WithMessage("An account transaction is required when the amount is paid.");
RuleFor(x => x.DatePaid)
.NotNull()
.When(x => x.IsPaid == true)
.WithMessage("Please enter the date when the expense was paid.");
}
}
和事务子类:
public class TransactionValidator : TransactionBaseValidator
{
public TransactionValidator() : base()
{
}
}
这些可以有额外的验证规则,并且使用base()
构造函数调用基本规则。
我使用以下方法验证 Expense 对象:
var validator = new ExpenseValidator();
var results = validator.Validate(oExpense);
现在,这不会返回我以下列方式使用的复杂属性事务的验证:
oExpense.Transaction = new Transaction();
oExpense.Transaction.Amount = oExpense.Amount;
oExpense.Transaction.BankAccountID = ddlAccounts.SelectedItem.Value.ToInt();
oExpense.Transaction.TransactionDate = oExpense.DatePaid.Value;
oExpense.Transaction.IsWithdrawal = true;
oExpense.Transaction.Description = oExpense.Description;
oExpense.Transaction.IsDeleted = false;
// I dont set the below and it should give me validation error:
// oExpense.Transaction.EmployeeID = 10;
我没有设置 EmployeeID ,当我为费用对象调用验证器时,它应该给我验证错误,因为它对SetValidator()
Transaction 属性有,并且 Transaction 也不是我已经设置的 null new Transaction()
。
任何想法?