流利的NHibernate DateTime UTC [英] Fluent NHibernate DateTime UTC

查看:68
本文介绍了流利的NHibernate DateTime UTC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个流畅的nhibernate映射,以下列方式映射DateTime字段:

I would like to create a fluent nhibernate mapping to map a DateTime field in a following way:

  1. 保存时-保存UTC值
  2. 读取时-调整为本地时区值

实现此映射的最佳方法是什么?

What is the best way to achieve this mapping?

推荐答案

我个人将日期存储在UTC中,然后在读/写时在对象内进行转换.然后,您可以引用属性在映射中使用的后备字段(用这种方法做起来并不像"fluent"那样,但是您可以使用FluentNH来映射它).如果UTC值在代码中对您有价值,那么只需公开它即可.

Personally, I would store the date in the object in UTC, then convert within the object when reading/writing. You can then reference the backing field your property uses in the mapping (it's not quite as "fluent" to do it this way but you can use FluentNH to map this). If the UTC value might have value to you in code then just expose it.

public class MyClass
{
   ...

   //Don't map this field in FluentNH; this is for in-code use
   public DateTime MyDate 
   {
      get{return MyDateUTC.ToLocalTime();} 
      set{MyDateUTC = value.ToUniversalTime();}
   }

   //map this one instead; can be private as well
   public DateTime MyDateUTC {get;set;} 
}

...

public class MyClassMap:ClassMap<MyClass>
{
   public MyClassMap()
   {
      Map(x=>x.MyDateUTC).Column("MyDate");

      //if you made the UTC property private, map it this way instead:
      Map(Reveal.Member<DateTime>("MyDateUTC")).Column("MyDate");
   }
}

这篇关于流利的NHibernate DateTime UTC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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