0

In EntityFramework 6 I could do something like the following to change the defaults for a particular data type:

protected override void OnModelCreating(
   DbModelBuilder mb
) {
   mb
   .Properties<DateTime>()
   .Configure(config => 
      config
      .HasColumnType("datetime2")
      .HasPrecision(7)
   );

This saves having to specify these details for every single DateTime property in the DB.

Is there an equivalent way of changing property defaults in EF Core? There is no such Properties member on the EF Core ModelBuilder type.

Dave Cousineau
  • 12,154
  • 8
  • 64
  • 80

1 Answers1

0

I have created an extension method for this.

public static class ModelBuilderExtensions
{
    public static void Properties<TPropertyType>(
        this ModelBuilder modelBuilder,
        Action<IMutableProperty> configureAction
    )
    {
        modelBuilder
            .Model
            .GetEntityTypes()
            .SelectMany(entityType => entityType.GetProperties())
            .Where(entityProperty => typeof(TPropertyType) == entityProperty.ClrType)
            .ToList()
            .ForEach(configureAction);
    }
}

Then I can do something like this:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Properties<DateTimeOffset>(
        property =>
        {
            if (property.Name == nameof(Entity.CreatedAtUtc))
            {
                property.SetDefaultValueSql("CURRENT_TIMESTAMP AT TIME ZONE 'UTC'");
            }
        }
    );
}
Gabor
  • 3,021
  • 1
  • 11
  • 20
  • 1
    Which seems to be not needed since [EF Core 6](https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-6.0/whatsnew#pre-convention-model-configuration) – Guru Stron Jan 21 '23 at 00:04