RowVersion implementation on Entity Framework for PostgreSQL
Asked Answered
S

2

12

I am using Entity Framework 6 with PostgreSQL. I have an entity in which I want to prevent concurrency issues, following this documentation I added a RowVersion property with [Timestamp] attribute, however after saving changes to the entity the column RowVersion value stays the same in the database.

    [Timestamp]
    public byte[] RowVersion { get; set; }

Am I missing something or is there another way to handle it in PostgreSQL?

Selffertilization answered 7/3, 2017 at 14:40 Comment(3)
I finally changed the byte[] RowVersion property for a string xmin property, specific to PostgreSQL, with ConcurrencyCheck decorator.Crat
can you post the column definition? do you use npgsql to create the model? thanxNasia
I've just posted the column definition as an answerCrat
S
10
/// <summary>
/// Meant to validate concurrency en database update
/// This column is updates itself in database and only works in postgresql
/// </summary>
[ConcurrencyCheck]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
//[NotMapped]
public string xmin { get; set; }

Had to add [NotMapped] attribute just for the column not to be added in the migration, commented it after database-update.

Selffertilization answered 8/9, 2017 at 13:46 Comment(2)
Thank you. Do you do this in a partial class? I am in a "database first" scenarioNasia
hi there, just remove the setter of the xmin property, instead of using the [NotMapped] attribute. it should not be migrated.Backfill
B
10

Just an updated answer for EF Core in case anyone else wanders here.

The Npgsql framework has built-in support for this using the hidden system column xmin that the OP is using in his entity as a NotMapped property.

As referenced here, you can set the xmin column as a concurrency token within EF by calling the UseXminAsConcurrencyToken method on your entity within its OnModelCreating method via Fluent API (a Data Annotation is not available at this time as far as I'm aware).

For anyone already using Fluent API configurations, it's as simple as this:

public class AwesomeEntityConfiguration : IEntityTypeConfiguration<AwesomeEntity>
{
    public void Configure(EntityTypeBuilder<AwesomeEntity> builder)
    {
        builder.UseXminAsConcurrencyToken();
    }
}
Bartholomew answered 14/8, 2019 at 13:13 Comment(2)
really awesome!Levant
For real, this is great. Magic, even.Mabe

© 2022 - 2024 — McMap. All rights reserved.