I am trying to implement the solution given in Handling Concurrency with the Entity Framework in an ASP.NET MVC Application .
The article says:
Adding a Tracking Property to the Department Entity
In Models\Department.cs, add a tracking property:
[Timestamp] public Byte[] Timestamp { get; set; }
The Timestamp attribute specifies that this column will be included in the Where clause of Update and Delete commands sent to the database.
Since I'm using a model first approach, I followed steps 1 - 5 outlined in Creating a Timestamp column with Entity Framework
- Add a property named “Timestamp” to the entity in EF’s model
- Set the type to binary
- Set nullable to false
- Set StoreGeneratedPattern to Computed
- Set ConcurrencyMode to Fixed
When I update my code from the database model, the Models\Department.cs now contains
public virtual byte[] Timestamp
{
get;
set;
}
Then I used the metadata class to specify the Timestamp attribute:
// Metadata for Department entity
public class DepartmentMetadata
{
[Timestamp]
public byte Timestamp { get; set; }
}
Q1. I tested whether the value of the Timestamp
column is changing in case of row edits. It isn't.
EDIT 1 The problem was caused because the SQL Server column type was binary
, where it should have been of type timestamp
. Changing the data type fixed the issue of the Timestamp column not getting updated.
Q2. I was trying to modify the same entity (using "Open in new tab") to see if an OptimisticConcurrencyException
is thrown. It isn't. What am I doing wrong? Please help me understand, thanks.
The problem was caused because I had one ObjectContext per HTTP session, and so opening a new tab and testing it would NOT cause a concurrency exception.
来源:https://stackoverflow.com/questions/10682591/ef-concurrency-handling-with-timestamp-attribute-in-model-first-approach