Database Reference
In-Depth Information
has the current values for the name and phone number and the newly generated timestamp. At that instant, the entity
is in sync with the database.
With the UpdateAgent() procedure, Entity Framework automatically maps our Name and Phone properties to the
stored procedure's parameters as long as the property names and parameter names match. However, we've named
the timestamp parameter @TimeStamp_Original . This ensures that the original value for the TimeStamp property
is sent to the database when we call the stored procedure. The where clause on the update statement includes the
timestamp; if the timestamp value for the row in the database is different from the value in the entity, the update will
fail. Because no rows are updated, Entity Framework responds by throwing a DbUpdateConcurrencyException .
If the update succeeds, the new timestamp value is mapped to the TimeStamp property on the entity. At this point,
the entity and row in the table are once again synchronized.
For the DeleteAgent() procedure, Entity Framework once again maps the Name and TimeStamp properties to
the parameters of the procedure automatically. The where clause on the delete statement includes the primary key,
Name, and the timestamp value; this ensures that the row is deleted if, and only if, no intermediate update of the row
has occurred. If no row is deleted, Entity Framework will respond with a DbUpdateConcurrencyException .
Entity Framework relies on each of these stored procedures returning some indication of the number of rows
affected by the operation. We've crafted each procedure to return this value either using a select statement that
returns either one or zero rows, or the row count from the statement.
There are three ways, in order of precedence, that Entity Framework interprets the number of rows affected by
a stored procedure: the return value from ExecuteNonQuery() , the number of rows returned, or an explicit output
parameter (see Recipe 14-5).
The code in Listing 14-6 demonstrates that an intervening update, which we do out-of-band with the
ExecuteSqlCommand() method, causes a concurrency violation when we update Phillip Marlowe's phone number.
14-3. Reading Uncommitted Data
Problem
Your application requires fast concurrent access with as little database overhead as possible, so you want to read
uncommitted data using LINQ to entities.
Solution
Suppose you have an Employee entity like the one shown in Figure 14-4 . You want to insert a new employee, but
before the row is committed to the database, you want to read the uncommitted row into a different object context.
To do this, create nested instances of the TransactionScope class and set the IsolationLevel of the innermost scope to
ReadUncommitted , as shown in Listing 14-7. You will need to add a reference in your project to System.Transactions .
Figure 14-4. An Employee entity
 
Search WWH ::




Custom Search