Databases Reference
In-Depth Information
var order = context.Orders
.Include(“Order_Details”)
.Include(“Order_Details.Product”)
.First(o => o.OrderID == orderId);
order.Fulfill();
You need to place code like this, however, in ever y page that needs to execute the Fulfill
business rule, spilling the data access logic into the presentation layer , which is, in most
circumstances, not a good idea. One of the reasons to avoid it is that the Entity
Framework 4 forces you to hard-code the names of the entity classes and their properties
as string literals, which are fragile and prone to typos. Even if you address this problem
with string constants, it still means hard-coding the knowledge of all entities and relation-
ships necessary for a particular business rule in the presentation layer, possibly in multiple
places where the same method is called.
Implementing Entity Interaction Rules as Context Methods
When performance is important and data access logic needs to be encapsulated, it can be
beneficial to implement business rules in methods of the object context class instead of the
entity class. Here is how to reimplement the order fulfillment business rule in the
NorthwindEntities class:
public partial class NorthwindEntities
{
public void FulfillOrder(int orderId)
{
Order order = this.Orders
.Include(“Order_Details”).Include(“Order_Details.Product”)
.First(o => o.OrderID == orderId);
order.OrderStatus = (byte)DataModel.OrderStatus.Fulfilled;
order.ShippedDate = DateTime.Now;
foreach (Order_Detail orderItem in order.Order_Details)
orderItem.Product.UnitsInStock -= orderItem.Quantity;
}
}
The FulfillOrder method takes OrderID as a parameter and retrieves the Order entity, all
of its Order_Detail objects, and the related Product entities in a single roundtrip to the
database. When all entities are loaded in the context, the code performs the same steps
implemented in the Fulfill method earlier—update OrderStatus and ShippedDate and
decrement UnitsInStock .
This version of the FulfillOrder method assumes that the caller does not already have
the Order instance loaded from the database, so taking its primary key value as a parameter
is the best option. However, if the Order instance is already loaded, you can change or
 
Search WWH ::




Custom Search