Databases Reference
In-Depth Information
Saving changes inside of business rule methods also makes maintenance of automated
tests more difficult. Although the TransactionScope -based approach to enforcing test
isolation discussed in Chapter 8 will continue to work, saving changes from a method
under test requires additional disk access and makes the test slower. As the number of
automated tests increases, their performance becomes more and more important. By
keeping saving logic out of business rule methods, you reduce disk access and speed up
the tests.
Although there are no hard rules against this, it is usually a good idea to keep the persis-
tence logic out of the business rule methods and entity classes. Instead, it is better to save
changes in the business process code, which is usually implemented outside of the Entity
Framework context and invoked by the user. For example, a web page or a console appli-
cation is a better place to save changes.
Managing Transactions
Although the TransactionScope supports hierarchical transactions and you could put one
inside of a business rule method, you need to remember that transactions do not apply to
changes made in the memory of the application. For instance, you could modify the
FulfillOrder method to update the Order and Product entities inside of a
TransactionScope :
using (var transaction = new TransactionScope())
{
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;
transaction.Complete();
}
However, remember that the Order and Product entities are not saved to the database
here; they are merely modified in memory . The TransactionScope in this example encom-
passes only the query that retrieves the Order_Detail and Product entities from the data-
base. Because Microsoft SQL Server and other database servers already execute SQL queries
in transactions by default, using an explicit transaction here would only increase complex-
ity without adding any benefits. Instead, it is better to implement transaction logic in the
same place as the persistence logic—outside of the business rule methods, as shown in the
following example:
using (var transaction = new TransactionScope())
using (var context = new NorthwindEntities())
{
int orderId = // ...
 
Search WWH ::




Custom Search