EF CORE 2.1类型为datetime的所有属性的HasConversion
我以前使用DateTimeKindEntityMaterializerSource( Git )在读取实体时将所有DateTime转换为UTC因为未指定默认值.
I previously used DateTimeKindEntityMaterializerSource (Git) to convert all DateTime to UTC when reading entities because the default was unspecified.
使用EF核心2.1,DateTimeKindEntityMaterializerSource不再起作用,但我们实际上可以做到这一点
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));
但是,我有许多DateTime属性,我希望有一种方法可以对DateTime类型的所有属性进行转换.
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.
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.
在此之前,您可以在OnModelCreating
覆盖的末尾使用典型的循环,在该循环中将发现所有实体类型和属性:
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);
}
}