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

查看:23
本文介绍了EF CORE 2.1 HasConversion 对 datetime 类型的所有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前使用 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 HasConversion 对 datetime 类型的所有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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