An Enthusiastic Programmer

Data Annotation - ConcurrencyCheck Attribute

|

Database concurrency refers to situations in which multiple users take part in trying to modify the same data. Let us deep in this scenario in two users are trying to change the order state simultaneously. Two users booked the same order, which should never happen. How do we avoid it? One of its solutions is to apply concurrency checks.

Entity Framework 6 and Entity Framework Core both supports optimistic concurrency control, which can solve the above problem. When applied the ConcurrencyCheck to a property, the corresponding column in the database table will use the where clause complete the optimistic concurrency check.

We have known that the Timestamp is the mechanism that applied the optimistic concurrency check. more details about Timestamp check here.

let’s look at the below example:

    public class Student
    {
        public int Id { set; get; }
        [ConcurrencyCheck]
        public string name { set; get; }
    }

In the above example, the ConcurrencyCheck is applied to the name property of the Student entity class. So the EF will include the name column in the UPDATE statement to check for optimistic concurrency.

using (var context = new SchoolContext()) {
    //add Student class
    context.student.Add(new Student(){name = "kobe"});
    context.SaveChanges();

    Student kobe = context.student.Where<Student>(st=>st.name.Equals("kobe")).FirstOrDefault();
    kobe.name = "kobe bryant";
    context.SaveChanges();
}

the above example will execute the fellowing UPDATE statement on SaveChanges(), where it includes the name in the where clause.

exec sp_executesql N'SET NOCOUNT ON;
UPDATE [student] SET [name] = @p0
WHERE [Id] = @p1 AND [name] = @p2;
SELECT @@ROWCOUNT;
',N'@p1 int,@p0 nvarchar(4000),@p2 nvarchar(4000)',@p1=1,@p0=N'kobe bryant',@p2=N'kobe'

Comments