EF Concurrency Handling with Timestamp attribute in Model First approach

笑着哭i 提交于 2019-12-18 16:59:48

问题


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

  1. Add a property named “Timestamp” to the entity in EF’s model
  2. Set the type to binary
  3. Set nullable to false
  4. Set StoreGeneratedPattern to Computed
  5. 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.


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!