Linq to SQL DateTime 值是本地的(Kind=Unspecified) - 我如何使它成为 UTC?
- 作者: 再也不会用心爱
- 来源: 51数据库
- 2022-12-08
问题描述
是否有一种(简单的)方法可以告诉 Linq To SQL 类特定的 DateTime 属性应被视为 UTC(即默认情况下,DateTime 类型的 Kind 属性为 Utc),或者是否有一个 '清洁"的解决方法?
Isn't there a (simple) way to tell Linq To SQL classes that a particular DateTime property should be considered as UTC (i.e. having the Kind property of the DateTime type to be Utc by default), or is there a 'clean' workaround?
我的应用服务器上的时区与 SQL 2005 Server 不同(不能更改任何),并且没有一个是 UTC.当我将 DateTime 类型的属性保留到 dB 时,我使用 UTC 值(因此 db 列中的值是 UTC),但是当我读回值(使用 Linq To SQL)时,我得到了 DateTime 的 .Kind 属性值为未指定".
The time zone on my app-server is not the same as the SQL 2005 Server (cannot change any), and none is UTC. When I persist a property of type DateTime to the dB I use the UTC value (so the value in the db column is UTC), but when I read the values back (using Linq To SQL) I get the .Kind property of the DateTime value to be 'Unspecified'.
问题是,当我将其转换"为 UTC 时,需要 4 小时.这也意味着当它被序列化时,它在客户端以 4 小时的错误偏移量结束(因为它是使用 UTC 序列化的).
The problem is that when I 'convert' it to UTC it is 4 hours off. This also means that when it is serialized it it ends up on the client side with a 4 hour wrong offset (since it is serialized using the UTC).
推荐答案
生成的 LinqToSql 代码提供了扩展点,因此您可以在加载对象时设置值.
The generated LinqToSql code provides extensibility points, so you can set values when the objects are loaded.
关键是创建一个分部类来扩展生成的类,然后实现OnLoaded分部方法.
The key is to create a partial class which extends the generated class, and then implement the OnLoaded partial method.
例如,假设您的类是 Person,那么您在 Blah.designer.cs 中有一个生成的部分 Person 类.
For instance, let's say your class is Person, so you have a generated partial Person class in Blah.designer.cs.
通过创建一个新类(必须在不同的文件中)来扩展分部类,如下所示:
Extend the partial class by creating a new class (must be in a different file), as follows:
public partial class Person {
partial void OnLoaded() {
this._BirthDate = DateTime.SpecifyKind(this._BirthDate, DateTimeKind.Utc);
}
}
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
