Databases Reference
In-Depth Information
This section discusses these approaches and some of the trade-offs you must take
into consideration when choosing how to implement entity interaction rules in your
application.
Implementing Entity Interaction Rules in BeforeSave Methods
You can use the
BeforeSave
“trigger” methods to implement not only property interaction
rules, but entity interaction rules as well. For instance, you could change the BeforeSave
method of the
Order
entity class to detect if the
OrderStatus
property changed from
Paid
to
Fulfilled
and update the
UnitsInStock
property of all Product entities purchased in
this Order. The code example that follows illustrates how the implementation could look:
partial class Order : ISavableObject
{
public void BeforeSave(ObjectStateEntry stateEntry)
{
byte? oldStatus = (byte)DataModel.OrderStatus.Draft;
if (stateEntry.State == EntityState.Modified)
oldStatus = stateEntry.OriginalValues.Get(() => this.OrderStatus);
if (this.OrderStatus == (byte)DataModel.OrderStatus.Submitted &&
oldStatus == (byte)DataModel.OrderStatus.Draft)
{
this.ShippedDate = DateTime.Now;
foreach (Order_Detail orderItem in this.Order_Details)
orderItem.Product.UnitsInStock -= orderItem.Quantity;
}
}
}
Although this approach is viable for trivial scenarios such as in this example, it quickly
becomes overwhelmingly difficult to maintain as the number of rules and their complex-
ity increases. One of the reasons this happens is because the code is
guessing
what the
presentation layer is trying to accomplish. When only the
OrderStatus
property is chang-
ing from
Paid
to
Fulfilled
, it is easy to see what is going on, but what if another prop-
erty of the Order entity changes as well? For example, you could have another business
rule tied to the
ShipVia
property of the Order entity to calculate the shipping fee (the
Freight
property) depending on the shipping option selected by the customer. If the
OrderStatus
changes to
Fulfilled
at the same time
with the
ShipVia
property, does it
mean an employee has chosen a different shipper to expedite the customer's order at no
additional cost
or
that the customer stopped by to pick up the order from our physical
store and you need to refund the shipping fee? It is impossible to answer this question in
the
business
layer of the application because it depends on how the
presentation
layer is
implemented.