.net - 在 Model First 方法中使用时间戳属性进行 EF 并发处理

标签 .net entity-framework-4 optimistic-concurrency

我正在尝试实现 Handling Concurrency with the Entity Framework in an ASP.NET MVC Application 中给出的解决方案.

文章说:

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.



因为我使用的是 模型第一 方法,我遵循了 Creating a Timestamp column with Entity Framework 中概述的步骤 1 - 5
  • 向 EF 模型中的实体添加一个名为“Timestamp”的属性
  • 将类型设置为二进制
  • 将 nullable 设置为 false
  • 将 StoreGeneratedPattern 设置为已计算
  • 将并发模式设置为固定

  • 当我从数据库模型更新我的代码时,Models\Department.cs 现在包含
        public virtual byte[] Timestamp
        {
            get;
            set;
        }
    

    然后我使用元数据类来指定 Timestamp 属性:
    // Metadata for Department entity
    public class DepartmentMetadata
    {
        [Timestamp]
        public byte Timestamp { get; set; }
    }
    

    一季度。 我测试了Timestamp的值是否在行编辑的情况下,列会发生变化。不是。

    编辑 1 问题是由于 SQL Server 列类型为 binary 引起的。 ,它应该是类型 timestamp .更改数据类型修复了时间戳列未更新的问题。

    Q2。 我试图修改同一个实体(使用“在新选项卡中打开”)来查看 OptimisticConcurrencyException被抛出。不是。我究竟做错了什么?请帮我理解,谢谢。

    Screenshot of my <code>Timestamp</code> property

    最佳答案

    这个问题是因为我每个 HTTP session 有一个 ObjectContext,所以打开一个新选项卡并测试它会 不是 导致并发异常。

    关于.net - 在 Model First 方法中使用时间戳属性进行 EF 并发处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10682591/

    相关文章:

    sql-server - 是否可以限制 Entity Framework 使用的连接数?

    nhibernate - Entity Framework 中是否有与 NHibernate 的 <component> 等效的东西?

    java - 使用 JPA/Hibernate 在无状态应用程序中进行乐观锁定

    .net - MySql .Net 连接器是特定于版本的

    c# - 如何检测父进程的关闭?

    entity-framework - Entity Framework 数据注释和多语言

    user-interface - 对于乐观并发失败,什么是好的最终用户消息

    c# - Type.GetType() 和 Assembly.GetType() 返回不同的结果

    c# - 获取 'excelcnv.exe' 位置