1

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;
    }

 }
4
  • have you looked at this? stackoverflow.com/a/6554939/5984 Commented Dec 12, 2013 at 14:31
  • what are you trying to achieve? why do you have 2 separate db context? Are you using the ConcurrencyCheckAttribute for the timestamp or this is a custom solution? If so then what is your goal (again)? Commented Dec 12, 2013 at 14:33
  • sorry it was my mistake. I edited code. there is only SchoolContext. Commented Dec 12, 2013 at 15:12
  • You have to use optimistic concurrency as described. It is the only way to do the check while updating. Your approach always leaves room for conflicts between the check and the actual update. Commented Dec 12, 2013 at 20:41

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.