2
votes

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
Regarding rehydration with local time, that really should be a presentation concern. Otherwise, you might end up storing mixed dates. - David Peden
well, actually, my question is still valid, since the link you reference just mentions that this should be done with a custom mapping, but doesn't provide the example code. I was hoping for a solution where the mapping automagically adjusted the times as needed - Alex
To do that, check out this post: stackoverflow.com/questions/242022/…. You'll in the NullSafeGet, you should return dateTime.ToLocalTime();. - David Peden

1 Answers

2
votes

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