如何指定从 EntityFramework 检索的 DateTime 对象应为 DateTimeKind.UTC

How to specify that DateTime objects retrieved from EntityFramework should be DateTimeKind.UTC(如何指定从 EntityFramework 检索的 DateTime 对象应为 DateTimeKind.UTC)

本文介绍了如何指定从 EntityFramework 检索的 DateTime 对象应为 DateTimeKind.UTC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 C# 程序,其中所有 DateTime 对象都是 DateTimeKind.UTC.将对象保存到数据库时,它按预期存储 UTC.但是,在检索它们时,它们是 DateTimeKind.Unspecified.在 C# 中创建 DateTime 对象时,有没有办法告诉实体框架(代码优先)始终使用 DateTimeKind.UTC?

I have C# program where all DateTime objects are DateTimeKind.UTC. When saving the objects to the database it stores UTC as expected. However, when retrieving them, they are DateTimeKind.Unspecified. Is there a way to tell Entity Framework (Code First) when creating DateTime objects in C# to always use DateTimeKind.UTC?

推荐答案

不,没有.它实际上是 DateTimeKind.Unspecified.

No, there's not. And it's actually DateTimeKind.Unspecified.

但是,如果您担心支持多个时区,则应考虑使用 日期时间偏移.它就像一个常规的 DateTime,只是它不代表时间的透视",它代表一个绝对视图,其中 3PM (UTC - 3) 等于 4PM (UTC - 2).DateTimeOffset 包含 DateTime 和时区,EntityFramework 和 SQL Server 都支持.

However, if you are concerned about supporting multiple timezones, you should consider using DateTimeOffset. It's like a regular DateTime, except that it does not represent a "perspective" of time, it represents an absolute view, in which 3PM (UTC - 3) equals 4PM (UTC - 2). DateTimeOffset contains both the DateTime and the time zone and it's supported by both EntityFramework and SQL Server.

这篇关于如何指定从 EntityFramework 检索的 DateTime 对象应为 DateTimeKind.UTC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何指定从 EntityFramework 检索的 DateTime 对象应为 DateTimeKind.UTC

基础教程推荐