我不認爲有一個開箱即用解決方案,會做什麼(即你的域驗證領帶到您的分貝)
但一些聰明的,我們可以實現的東西,將節省您大量的額外工作。
我建議考慮使用一個框架像FluentValidation
這將允許你創建你可以用它來在整個應用程序層驗證您的域模型驗證類。
因此,每個模型只需要一個驗證類,然後數據庫會讓您知道該級別的任何問題。
或者,如果您需要,您可以創建一個驗證類,每個圖層,每個場景或真正你想要的。
看一看一些執行代碼CodePlex從下面:
using FluentValidation;
public class CustomerValidator: AbstractValidator<Customer> {
public CustomerValidator() {
RuleFor(customer => customer.Surname).NotEmpty();
RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Please specify a first name");
RuleFor(customer => customer.Company).NotNull();
RuleFor(customer => customer.Discount).NotEqual(0).When(customer => customer.HasDiscount);
RuleFor(customer => customer.Address).Length(20, 250);
RuleFor(customer => customer.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
}
private bool BeAValidPostcode(string postcode) {
// custom postcode validating logic goes here
}
}
Customer customer = new Customer();
CustomerValidator validator = new CustomerValidator();
ValidationResult results = validator.Validate(customer);
bool validationSucceeded = results.IsValid;
IList<ValidationFailure>
failures = results.Errors;
好了,所以你怎麼處理的值,如最大長度是多少?如果數據庫中某個字段的最大長度爲10,您是否會將值10硬編碼到您的圖層中?或者你使用中央配置? – Chris 2012-02-16 03:48:56
@ChrisPaynter:10被烘焙到類定義中。所有圖層都依賴於對象來確定它是否有效。 – NotMe 2012-02-16 03:52:51
非常感謝。所以我猜你正在使用一個公共const int? – Chris 2012-02-16 04:27:38