Getting a the new value of RowVersion using Entity Framework 6

asp.net-mvc asp.net-mvc-5 entity-framework entity-framework-6

Question

Is is possible, to get the new value of RowVersion using the same DbContext, without reloading the entity from the database?

Scenario:

  • Load data into editor form
  • Save new values
  • The row in the table gets updated, new value of RowVersion is generated
  • However, the saved entity still holds the old value of RowVersion, so the new value can not be passed back to the client

All concurrency control articles are usually concerned only with preventing the update (e.g. see 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. I would like to avoid this redirect.

Accepted Answer

Thanks to grennis, I found out the source of my problems.

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. 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). 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

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

SQL Profiler, it was nice knowing you :-)




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why