Databases Reference
In-Depth Information
perhaps create an overloaded version of the FulfillOrder method so that it takes an
entity instance as a parameter instead. The code sample that follows shows an example of a
possible implementation. As you can see, instead of querying the Order entity set, you can
query the Order_Details entity set and reduce the number of Include calls to one:
public partial class NorthwindEntities
{
public void FulfillOrder( Order order )
{
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;
}
}
Although the second version of the Fulfill O rder feels more “object-oriented” in that it
takes an Order object as a parameter instead of a primitive primary key value, your choice
of design approach should be driven by the concrete scenarios you need to implement. If
the orders will be marked as fulfilled one at a time from an ASP.NET web page, the calling
code only has the primary key value stored in the ViewState of the page, and the first
version of the FulfillOrder method will work best. The more elegant second version of
the FulfillOrder method might work better only in a scenario where multiple orders have
already been loaded from the database and the overhead of making an additional database
call to retrieve the order instance will not be incurred. In other words, the second style of
methods works better for implementing granular business rules that are a part of a larger
business process.
NOTE
Implementing entity interaction rules in object context methods and removing depen-
dency on lazy loading helps improve not only performance , but also correctness of the
application. Unless the code reliant on lazy loading explicitly checks that it is enabled,
the lazy loading option could be accidentally or intentionally turned off, making an order
appear empty when, in fact, its items and products simply have not been loaded from
the database.
On the downside, implementing business rules as context methods can feel awkward
depending on where you think the method belongs. For instance, if you feel strongly
that fulfillment is the behavior of the Order class, moving the Fulfill method to the
NorthwindEntities class would mean breaking its encapsulation.
 
Search WWH ::




Custom Search