Database Reference
In-Depth Information
The strategy we use in Listing 14-8 is to obtain the DbEntityEntry that is tracking changes to our ForumPost
object and then refresh the OriginalValues property with the values currently in the data store. Armed with the latest
TimeStamp property, our call to SaveChanges() should succeed. There is a chance, especially in a highly concurrent
environment, that some intervening update could occur to change the row before our update hits the database. If
this occurs, Entity Framework will throw a DbUpdateConcurrencyException . If that should occur, we try to repeat our
DbEntityEntry refresh in the catch block and call SaveChanges() again.
Even with these two approaches in place, it is still possible for an intervening update to occur between the refresh
and the time the update is executed on the database.
14-5. Getting Affected Rows from a Stored Procedure
Problem
You want to return the number of rows affected by a stored procedure through an output parameter.
Solution
Entity Framework uses the number of rows affected by an operation to determine whether the operation succeeded or
the operation failed because of a concurrency violation. When using stored procedures (see Recipe 14-2), one of the
ways to communicate the number of rows affected by an operation is to return this value as an output parameter of
the stored procedure.
Let's suppose you have a model like the one shown in Figure 14-6 .
Figure 14-6. Our model with the Account entity
To return the number of rows affected by the stored procedures mapped to the insert, update, and delete actions,
do the following:
1.
Create the stored procedures in the database using the code in Listing 14-9.
Listing 14-9. The Stored Procedures for the Insert, Update, and Delete Actions
create procedure [Chapter14].[UpdateAccount]
(@AccountNumber varchar(50), @Name varchar(50), @Balance decimal, @TimeStamp TimeStamp,
@RowsAffected int output)
as
begin
update Chapter14.Account
output inserted.TimeStamp
set Name = @Name, Balance = @Balance
 
Search WWH ::




Custom Search