EntityFrameworkCore.Generator icon indicating copy to clipboard operation
EntityFrameworkCore.Generator copied to clipboard

date/time value generator + .net conversion

Open Strandedpirate opened this issue 1 year ago • 1 comments

.Net & EF don't handle UTC date/time columns correctly out of the box. By default all date/time objects are created in .Net using DateTimeKind.Local.

This request:

  • allows the definition of a global date/time value generator.
  • allows the definition of a global date/time kind.

EFG Configuration

mapping:
  namespace: "{Project.Namespace}.Domain.EntityConfiguration"
  directory: '{Project.Directory}\My.Domain\EntityConfiguration'
  document: false
  dateTimeKind: Utc # configures the conversion of date/time columns as UTC in .Net
  dateTimeDefaultValueGenerator: UtcValueGenerator # defines the default date/time value generator

Produces

builder.Property(t => t.CreatedOn)
    .IsRequired()
    .HasColumnName("CreatedOn")
    .HasColumnType("datetime2(1)")
    .HasDefaultValueSql("(sysutcdatetime())")
    .HasConversion(t => t, t => DateTime.SpecifyKind(t, DateTimeKind.Utc))
    .HasValueGenerator<UtcValueGenerator>();

Sample UtcValueGenerator

internal class UtcValueGenerator : ValueGenerator<DateTime>
{
    public override bool GeneratesTemporaryValues => false;

    public override DateTime Next([NotNullAttribute] EntityEntry entry)
    {
        return DateTime.UtcNow;
    }
}

Strandedpirate avatar Apr 08 '23 06:04 Strandedpirate

@pwelter34 what do you think about this pull request?

Strandedpirate avatar Dec 14 '23 18:12 Strandedpirate