我以前使用DateTimeKindEntityMaterializerSource(
Git)在读取实体时将所有DateTime转换为UTC,因为默认是未指定的.
使用EF核心2.1,DateTimeKindEntityMaterializerSource不再有效,但我们实际上可以这样做
builder .Entity<ESDataQuotation>() .Property(e => e.CreatedDate) .HasConversion(v => v,v => DateTime.SpecifyKind(v,DateTimeKind.Utc));
解决方法
摘自EF Core 2.1
Value Conversions文档主题:
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覆盖末尾的典型循环来发现所有实体类型和属性:
var dateTimeConverter = new ValueConverter<DateTime,DateTime>( v => 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); } }