Data Annotations - Timestamp Attribute in EF 6 & EF Core

EF 6 and EF Core both include the Timestamp data annotation attribute. It can only be applied once in an entity class to a byte array type property. It creates a column with timestamp data type in the SQL Server database. Entity Framework API automatically uses this Timestamp column in concurrency check on the UPDATE statement in the database.

using System.ComponentModel.DataAnnotations;

public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }
        
    [Timestamp]
    public byte[] RowVersion { get; set; }
}

In the above example, the Timestamp attribute is applied to the byte[] property of the Student entity. So, EF will create a column named RowVersion with timestamp data type in the Students table in the SQL Server database, as shown below.

dataannotations TimeStamp attribute

This timestamp column will be included in the where clause whenever you update an entity and call the SaveChanges method.

using(var context = new SchoolContext()) 
{
    var std = new Student()
    {
        StudentName = "Bill"
    };

    context.Students.Add(std);
    context.SaveChanges();

    std.StudentName = "Steve";
    context.SaveChanges();
}

The above code will execute the following UPDATE statement in the database.

exec sp_executesql N'UPDATE [dbo].[Students]
SET [StudentName] = @0
WHERE (([StudentId] = @1) AND ([RowVersion] = @2))
SELECT [RowVersion]
FROM [dbo].[Students]
WHERE @@ROWCOUNT > 0 AND [StudentId] = @1',N'@0 nvarchar(max) ,@1 int,@2 binary(8)',@0=N'Steve',@1=1,@2=0x00000000000007D1
go