I previously used DateTimeKindEntityMaterializerSource (Git) to convert all DateTime to UTC when reading entities because the default was unspecified.
With EF core 2.1 the DateTimeKindEntityMaterializerSource no longer works but we can actually do this
builder .Entity<ESDataQuotation>() .Property(e => e.CreatedDate) .HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc));
However, I have many properties of DateTime and I would like if there is a way to make the conversion for all property of type DateTime.
Entity Framework (EF) Core, Microsoft's object-to-database mapper library for . NET Framework, brings performance improvements for data updates in version 7, Microsoft claims. The performance of SaveChanges method in EF7 is up to 74% faster than in EF6, in some scenarios.
IEntityTypeConfiguration<TEntity> InterfaceAllows configuration for an entity type to be factored into a separate class, rather than in-line in OnModelCreating(ModelBuilder).
What Is A Value Converter? When dealing with EF Core data modeling, we may store data differently than how we handle it within the context of our application. We can use value converters to optimize database storage, write performance, and read latency, in addition to optimizing memory in our application.
The DbContext class has a method called OnModelCreating that takes an instance of ModelBuilder as a parameter. This method is called by the framework when your context is first created to build the model and its mappings in memory.
Excerpt from EF Core 2.1 Value Conversions documentation topic:
There is currently no way to specify in one place that every property of a given type must use the same value converter. This feature will be considered for a future release.
Until then, you can use the typical loop at the end of the OnModelCreating
override where all entity types and properties are discovered:
var dateTimeConverter = new ValueConverter<DateTime, DateTime>( v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)); foreach (var entityType in modelBuilder.Model.GetEntityTypes()) { foreach (var property in entityType.GetProperties()) { if (property.ClrType == typeof(DateTime) || property.ClrType == typeof(DateTime?)) property.SetValueConverter(dateTimeConverter); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With