sdkarm
sdkarm

Reputation: 63

Entity Framework Concurrency control using "Timestamp" value check

For concurrency control i Write "VersionCheck" function in my Context class,I need to dynamically load Context object and check if version is the same as the current context object RowVersion. now i use switch statement. (code below) and also, Is there more convenient way for version control?

p.s. RowVersion is TimeStamp type in Database.

  public class SchoolContext : DbContext
  {
    public DbSet<Group> Groups { get; set; }
    public DbSet<Person> Persons { get; set; }

    public bool VersionCheck(string objName)
    {
        var dbc = new SchoolContext();
        byte[] bt1 = null;
        byte[] bt2 = null;

        switch (objName)
        {
            case "Person":
                dbc.Persons.Load();
                bt1 = dbc.Persons.SingleOrDefault(p => p.Id == 1).RowVersion;
                bt2 = this.Persons.Local.SingleOrDefault(p => p.Id == 1).RowVersion;
                break;
            case "Group":
                dbc.Groups.Load();
                bt1 = dbc.Groups.SingleOrDefault(p => p.Id == 1).RowVersion;
                bt2 = this.Groups.Local.SingleOrDefault(p => p.Id == 1).RowVersion;
                break;
        }

        if (bt1 == null && bt2 == null)
        {
            throw new Exception("One of the Variable is null!");
            return true;
        }
        for (int i = 0; i < bt1.Length; i++)
        {
            if (bt1[i] != bt2[i])
            {
                MessageBox.Show("Current object changed!");
                return false;
            }
        }
        return true;
    }

 }

Upvotes: 1

Views: 2277

Answers (1)

phil soady
phil soady

Reputation: 11348

Optimistic concurrency explained

The described approach looks like data corruption waiting to happen.
Unless you are locking the row or table during the time you read and check the rowversion, then it can change after to you have read it to check its value.

Use Optimistic concurrency paradigm properly.

eg https://stackoverflow.com/a/14718991/1347784

Upvotes: 1

Related Questions