EF CORE 2.1类型为datetime的所有属性的HasConversion [英] EF CORE 2.1 HasConversion on all properties of type datetime

查看:514
本文介绍了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.

推荐答案

EF Core 2.1的摘录

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);
    }
}

这篇关于EF CORE 2.1类型为datetime的所有属性的HasConversion的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆