问题
I would like to create a fluent nhibernate mapping to map a DateTime field in a following way:
- On save - Save the UTC value
- 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