Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF CORE 2.1 HasConversion on all properties of type datetime

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.

like image 372
Pilouk Avatar asked Jun 06 '18 19:06

Pilouk


People also ask

Is EF core faster than EF6?

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.

What is IEntityTypeConfiguration?

IEntityTypeConfiguration<TEntity> InterfaceAllows configuration for an entity type to be factored into a separate class, rather than in-line in OnModelCreating(ModelBuilder).

What are the value converters in EF?

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.

What is OnModelCreating in Entity Framework?

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.


1 Answers

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);     } } 
like image 64
Ivan Stoev Avatar answered Sep 17 '22 08:09

Ivan Stoev