Databases Reference
In-Depth Information
exception in the .NET code, calling RAISERROR in T-SQL does not interrupt the execution
of the stored procedure unless it is done from within a TRY block. This is why the
FulfillOrder method has a RETURN statement right after RAISERROR ; otherwise, the second
UPDATE statement, which modifies the UnitsInStock column of the Product table, would be
executed even for unpaid orders.
After creating the FulfillOrder stored procedure, you need to import its definition in the
NorthwindEntities entity model. As you recall from a discussion in Chapter 2, “Entity
Framework,” this requires two steps. First, you need to use the Entity Designer to update
the model from the database and create a definition of the stored procedure in the storage
model of the EDMX. Second, you need to use the Model Browser to create a function
import in the conceptual model , which generates a new method in the NorthwindEntities
class when the EDMX file is saved.
Because additional code is required to handle database errors, you do not want the stored
procedure method to be called directly by the presentation layer. Instead, you want the
function import to have a different name— SqlFulfillOrder —and have internal access so
that only the FulfillOrder method can call it and not the web application. Here is how
the FulfillOrder method will look after the optimization:
public void FulfillOrder(int orderId)
{
try
{
this.SqlFulfillOrder(orderId);
}
catch (EntityCommandExecutionException e)
{
HandleSqlException(e);
throw;
}
}
Note that the SqlFulfillOrder is called within a try/catch block because Entity
Framework reports database errors that occur when calling stored procedures as instances
of the EntityCommandExecutionException class. Because the code calling the FulfillOrder
method expects only ValidationException , the FulfillOrder method catches the
EntityCommandExecutionException instances and passes them to the HandleSqlException
method created earlier. In other words, the exception handling code implemented here
allows the order status validation now implemented in the T-SQL to continue throwing
ValidationException as if it was still implemented in the .NET code.
Side Effects of Stored Procedures
The performance improvement of reimplementing business rule methods as stored proce-
dures comes at a cost of introducing several undesirable side effects in your business layer
design:
Search WWH ::




Custom Search