Databases Reference
In-Depth Information
if (this.OrderDate.Value < DateTime.Today)
yield return new ValidationResult(
“The Order Date cannot be in the past”, new [] { “OrderDate” });
if (this.RequiredDate != null &&
this.RequiredDate <= this.OrderDate.Value.AddDays(3))
yield return new ValidationResult(
“The Required Date must be greater than Order Date + 3 days”,
new[] { “RequiredDate” });
Product product = this.Order_Details
.Where(item => item.Product.UnitsInStock < item.Quantity)
.Select(item => item.Product).FirstOrDefault();
if (product != null)
yield return new ValidationResult(product.ProductName + “ is out of stock”);
}
private IEnumerable<ValidationResult> ValidatePaidOrder(ValidationContext c)
{
// Validation logic specific to paid orders
return new ValidationResult[0];
}
private IEnumerable<ValidationResult> ValidateFulfilledOrder(ValidationContext c)
{
// Validation logic specific to fulfilled orders
return new ValidationResult[0];
}
}
Validation rules that are shared by all states of an entity can be implemented either declar-
atively by applying validation attributes or in the main Validate method of the entity
class. For complex entities that need to support large number of validation rules, you
might want to consider using the Strategy pattern ( Design Patterns: Elements of Reusable
Object-Oriented Software by Eric Gamma, Richard Helm, Ralph Johnson, and John Vlissides)
and moving validation rules specific to a particular state to a separate validation class.
However, for simple entities, where the number of rules is relatively small, a simple switch
statement showed in this example can do the same job without the overhead of introduc-
ing separate validation classes.
Validation of Related Entities
It might be challenging to determine the right place to implement validation logic that
requires information from related entities. And although it might seem that the
Order_Detail entity should be responsible for validating its Quantity property against the
 
Search WWH ::




Custom Search