是否有一种(简单的)方法可以告诉 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);
}
}
这篇关于Linq to SQL DateTime 值是本地的(Kind=Unspecified) - 我如何使它成为 UTC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!