Dom Sinclair
Dom Sinclair

Reputation: 2528

TimeStamp / Rowversion column with EF Core

I am trying to figure out how I should add a Timestamp/rowversion column to data tables in SQL Server via Entity Framework code first.

This is using EF Core V2.0.

I have tried two approaches to achieve this, the first:

public class Contact
{
    public int ContactId { get; set; }
    public string ContactName { get; set; }
    public string CompanyName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    [Timestamp]
    public byte[] RowVersion { get; set; }
}

The second via the fluent API:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    foreach (var entityType in modelBuilder.Model.GetEntityTypes())
    {
        modelBuilder.Entity(entityType.Name).Property<DateTime>("Inserted");
        modelBuilder.Entity(entityType.Name).Property<DateTime>("LastModified");
        modelBuilder.Entity(entityType.Name).Property<byte[]>  ("RowVersion");
    }
}

In both cases after I run Add-Migration, I get the following:

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.CreateTable(
        name: "Contacts",
        columns: table => new
        {
            ContactId    = table.Column<int>(type: "int", nullable: false)
                .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
            CompanyName  = table.Column<string>  (type: "nvarchar(max)", nullable: true),
            ContactName  = table.Column<string>  (type: "nvarchar(max)", nullable: true),
            FirstName    = table.Column<string>  (type: "nvarchar(max)", nullable: true),
            Inserted     = table.Column<DateTime>(type: "datetime2", nullable: false),
            LastModified = table.Column<DateTime>(type: "datetime2", nullable: false),
            LastName     = table.Column<string>  (type: "nvarchar(max)", nullable: true),
            RowVersion   = table.Column<byte[]>  (type: "varbinary(max)", nullable: true)
        },
        constraints: table =>
        {
            table.PrimaryKey("PK_Contacts", x => x.ContactId);
        }
    );
}

I would have expected the RowVersion column to be of type timestamp and for its nullable property to be false. Is this a limitation of EF Core or am I trying to do this incorrectly?

Upvotes: 1

Views: 6776

Answers (1)

Steve Macdonald
Steve Macdonald

Reputation: 1785

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<MyEntity>()
      .Property(b => b.MyVersionProperty)
      .IsRowVersion();
}

Upvotes: 0

Related Questions