In order to have a row version on an entity the documentation guides to do this:
class MyContext : DbContext
{
public DbSet<SomeEntity> SomeEntities { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<SomeEntity>()
.Property(b => b.Version)
.IsRowVersion();
}
}
public class SomeEntity
{
public int Id { get; set; }
public uint Version { get; set; }
}
Since many of my entities need this row version, how can I put it in a base class (or interface) and configure EF to automatically add row version for them?
public abstract class BaseEntity
{
public uint Version { get; set; }
}
public class SomeEntity1 : BaseEntity
{
public int Id { get; set; }
}
public class SomeEntity2 : BaseEntity
{
public int Id { get; set; }
}
Try conventions.
See Model bulk configuration
public class RowVersionConvention : IModelFinalizingConvention
{
public void ProcessModelFinalizing(IConventionModelBuilder modelBuilder,
IConventionContext<IConventionModelBuilder> context)
{
foreach (var property in modelBuilder.Metadata.GetEntityTypes()
.SelectMany(entityType =>
entityType.GetDeclaredProperties().Where(
property => property.ClrType == typeof(uint)
&& property.Name == "Version")))
{
property.Builder.HasColumnType("rowversion"); // xmin
}
}
}
Tested in Sql Server.
In PostgreSQL should be “xmin”, I think.
Add convention in DbContext:
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
configurationBuilder.Conventions.Add(_ => new RowVersionConvention());
}