Databases Reference
In-Depth Information
this.Validate(order);
if (order.OrderStatus != (byte)DataModel.OrderStatus.Paid)
{
throw new InvalidOperationException(
“Order status must be Paid for the order to be fulfilled”);
}
order.OrderStatus = (byte)DataModel.OrderStatus.Fulfilled;
order.ShippedDate = DateTime.Now;
IQueryable<Order_Detail> orderItems = this.Order_Details
.Include(“Product”)
.Where(od => od.OrderID == order.OrderID);
foreach (Order_Detail orderItem in orderItems)
orderItem.Product.UnitsInStock -= orderItem.Quantity;
}
}
Remember that all modified entities go through the mandatory validation before they are
persisted in the database in the SaveChanges method that was overidden in the
UnleashedObjectContext . Although you could also call the Validate method at the end of
FulfillOrder as well to check the modified Order and Product entities, doing so would
most likely result in the same validation rules executed two times without any additional
changes made to the entities in between. In other words, forcing validation of entity
objects at the end of business rule methods is usually redundant and can lead to unneces-
sary performance problems if validation rules require access to related entities that have to
be retrieved from the database.
Forcing validation of entity objects in the beginning of business rule methods can also be
redundant. If a business rule method, such as the overload of FulfillOrder that takes
OrderID as a parameter, is responsible for retrieving an entity object from the database,
you can often assume that the entity object is still valid because it already passed all vali-
dation rules last time it was saved to the database. In the FulfillOrder( Order ) method,
the calling code could have changed the Order entity, making its explicit validation
potentially worthwhile. However, in the FulfillOrder( Int32 ) method, you can safely
assume that the Order entity retrieved from the database is still valid, making the explicit
revalidation unnecessary.
Although reusing entity- and property-level validation rules in business rule methods
helps to improve correctness of your application and its data integrity, it comes at the cost
of additional resources required to perform the extra checks. It is usually not a good idea
to do this in production code. However, you can benefit from the additional validation in
business rule methods during active development and testing of your application by condi-
tionally compiling it . Here is how you could change the FulfillOrder method to validate the
Order object only in the Debug configuration of the DataModel project, which defines the
DEBUG compiler symbol.
 
Search WWH ::




Custom Search