简体   繁体   English

使用Entity Framework 6获取RowVersion的新值

[英]Getting a the new value of RowVersion using Entity Framework 6

Is is possible, to get the new value of RowVersion using the same DbContext, without reloading the entity from the database? 是否可以使用相同的DbContext获取RowVersion的新值,而无需从数据库中重新加载实体?

Scenario: 场景:

  • Load data into editor form 将数据加载到编辑器表单中
  • Save new values 保存新值
  • The row in the table gets updated, new value of RowVersion is generated 表中的行得到更新,生成RowVersion的新值
  • However, the saved entity still holds the old value of RowVersion, so the new value can not be passed back to the client 但是,保存的实体仍然保留RowVersion的旧值,因此无法将新值传递回客户端

All concurrency control articles are usually concerned only with preventing the update (eg see this ). 所有并发控制文章通常只关注阻止更新(例如,参见this )。 However, in the example from the article, a successful update is followed by a redirect to page, where the saved entity is read again and now it has a new RowVersion value. 但是,在本文的示例中,成功更新后将重定向到页面,在该页面上再次读取保存的实体,现在它具有新的RowVersion值。 I would like to avoid this redirect. 我想避免这种重定向。

Thanks to grennis, I found out the source of my problems. 感谢grennis,我找到了问题的根源。

I defined the interface and an entity like 我定义了接口和一个像

public interface IRowVersion
{
    // Attention: this will not be "inherited" by the implementing class !!!
    [Timestamp]
    byte[] VersionStamp { get; set; }
}

public class Directory : IRowVersion
{
    [Key]
    public int Id { get; set; }

    public string Title { get; set; }
    public string Description { get; set; }

    // If this attribute is missing here, then row version is used
    // My initial version was without this attribute
    [Timestamp]
    public byte[] VersionStamp { get; set; }
}

In my problematic version, I thought that having the attribute on the interface property is enough. 在我的问题版本中,我认为在interface属性上具有该属性就足够了。 However, the attribute must be explicitly applied on the entity's property. 但是,必须将属性显式应用于实体的属性。 Otherwise it will not be used at all (not even as the part of update SQL statement). 否则,它将根本不会使用(甚至不会用作更新SQL语句的一部分)。 The value was updated only because the DB updates the column value automatically and of course, at next read, I got the new value. 仅因为数据库自动更新列值而更新了该值,所以当然,在下次读取时,我得到了新值。

Not entirely related to the problem, but still worth mentioning... The following is really a killer feature of EF6 与问题不完全相关,但仍然值得一提...以下是EF6的杀手er

ctx.Database.Log = s => Debug.Write(s);

SQL Profiler, it was nice knowing you :-) SQL Profiler,很高兴认识您:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM