Database Reference
In-Depth Information
The following is the output of the code in Listing 14-12:
Updating Joan Williams's enrollment date
[Apply rogue update]
Exception: Store update, insert, or delete statement affected an unexpected number of rows (0).
Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager
entries.
How It Works
In Listing 14-12, the code retrieves a student entity. An intervening update occurs to the Person table before the code
updates the EnrollmentDate property on the entity and calls SaveChanges() . Entity Framework detects the concurrency
violation when updating the tables in the database because the value in the TimeStamp column in the Person table
does not match the TimeStamp value in the student entity. Entity Framework applies concurrency at the entity level.
Before the Student table is updated, the Person table is updated with a meaningless or dummy update and the new
TimeStamp value is obtained. This can be seen in the trace in Listing 14-13. If this update fails to affect any rows, Entity
Framework knows that the underlying table was changed since the last read. This would cause Entity Framework to
throw an OptimisticConcurrencyException .
Listing 14-13. Entity Framework Updates the TimeStamp in the Base Table Prior to Performing the Update in
the Derived Table
exec sp_executesql N'declare @p int
update [Chapter14].[Person]
output [Inserted].[TimeStamp]
set @p = 0
where (([PersonId] = @0) and ([TimeStamp] = @1))
select [TimeStamp]
from [Chapter14].[Person]
where @@ROWCOUNT > 0 and
[PersonId] = @0',N'@0 int,@1 binary(8)',@0=10,@1=0x0000000000007D19
Note that, if the rogue update occurred on the Student table in the database, the TimeStamp column in the
Person table would not have been changed and Entity Framework would not have detected a concurrency violation.
This is an important point to remember. The concurrency detection illustrated here extends just to rogue updates to
the base entity.
14-7. Generating a Timestamp Column with Model First
Problem
You want to use Model First, and you want an entity to have a TimeStamp property for use in optimistic concurrency.
 
Search WWH ::




Custom Search