Fluent NHibernate DateTime UTC

一笑奈何 提交于 2021-02-07 09:45:48

问题


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

  1. On save - Save the UTC value
  2. On read - Adjust to local time zone value

What is the best way to achieve this mapping?


回答1:


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");
   }
}


来源:https://stackoverflow.com/questions/9670906/fluent-nhibernate-datetime-utc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!