LINQ到SQL DateTime值是本地(KIND =未指定) - 如何使它UTC? [英] Linq to SQL DateTime values are local (Kind=Unspecified) - How do I make it UTC?

查看:121
本文介绍了LINQ到SQL DateTime值是本地(KIND =未指定) - 如何使它UTC?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是不是有(简单)的方式告诉Linq到一个特定的日期时间属性应(即具有DateTime类型是UTC在默认情况下的一种属性)视为UTC,或SQL类是有'干净的解决方法吗?

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服务器(不能改变的话),并没有为UTC。当我坚持DateTime类型的属性到数据库我用的是UTC值(所以在数据库列是UTC的值),但是当我读回值(使用LINQ to SQL)我得到的日期时间的.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 code提供了扩展点,这样你就可以加载的对象时设置的值。

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.

例如,假设你的类是,让你有一个产生的部分 Blah.designer.cs

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到SQL DateTime值是本地(KIND =未指定) - 如何使它UTC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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