在Model First方法中使用Timestamp属性的EF并发处理 [英] EF Concurrency Handling with Timestamp attribute in Model First approach
问题描述
我试图实现使用ASP.NET MVC应用程序中的实体框架处理并发性
I am trying to implement the solution given in Handling Concurrency with the Entity Framework in an ASP.NET MVC Application .
文章说:
向部门实体添加跟踪属性
在Models\Department.cs中,添加跟踪属性:
Adding a Tracking Property to the Department Entity
In Models\Department.cs, add a tracking property:
[Timestamp]
public Byte[] Timestamp { get; set; }
Timestamp属性指定此列将包含在发送的更新和删除命令的Where子句中到数据库。
The Timestamp attribute specifies that this column will be included in the Where clause of Update and Delete commands sent to the database.
由于我使用的是模型,方法,我遵循步骤1 - 5概述在使用实体框架创建时间戳列
Since I'm using a model first approach, I followed steps 1 - 5 outlined in Creating a Timestamp column with Entity Framework
- 在EF模型中向实体添加名为Timestamp的属性
- 设置将类型转换为二进制
- 将可空值设置为false
- 将StoreGeneratedPattern设置为Computed
- 将并发模式设置为Fixed
- 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
当我从数据库模型更新代码时,Models\Department.cs现在包含
When I update my code from the database model, the Models\Department.cs now contains
public virtual byte[] Timestamp
{
get;
set;
}
然后我使用元数据类来指定Timestamp属性:
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。我测试了在行编辑的情况下, Timestamp
列正在更改。不是
Q1. I tested whether the value of the Timestamp
column is changing in case of row edits. It isn't.
编辑1 问题是因为SQL Server列类型为 binary
应该是它的类型为 timestamp
。
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。我正在尝试修改相同的实体(使用在新选项卡中打开),以查看是否抛出了 OptimisticConcurrencyException
。不是我究竟做错了什么?请帮助我理解,谢谢。
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.
推荐答案
问题是因为我每个HTTP会话有一个ObjectContext,因此,打开一个新的选项卡并进行测试将不导致并发异常。
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.
这篇关于在Model First方法中使用Timestamp属性的EF并发处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!