我想创建一个流畅的 nhibernate 映射来通过以下方式映射 DateTime 字段:
- 保存时 - 保存 UTC 值
- 读取时 - 调整为本地时区值
实现此映射的最佳方法是什么?
最佳答案
就我个人而言,我会以 UTC 格式将日期存储在对象中,然后在读/写时在对象内进行转换。然后,您可以引用您的属性在映射中使用的支持字段(这种方式不太“流畅”,但您可以使用 FluentNH 来映射它)。如果 UTC 值在代码中可能对您有值(value),那么只需公开它即可。
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");
}
}
关于c# - Fluent NHibernate 日期时间 UTC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9670906/