ric*_*ard 5 nhibernate configuration datetime utc fluent-nhibernate
这个SO问题谈到"将流利的nhibernate配置的DateTime重新水化为Utc而不是未指定".
该问题后面的答案之一有:
Map(x => x.EntryDate).CustomType<UtcDateTimeType>();
Run Code Online (Sandbox Code Playgroud)
这适用于一个实体上的一个属性.
我想知道是否有一种方法可以指定所有日期时间属性都作为UTC存储在数据库中.
这是可能的,如果是的话,怎么样?
流畅的NHibernate的方式是 Convention
James Gregory于2012年4月3日编辑本页·1修订版
...
约定是使用一组接口和基类构建的,每个接口和基类根据您正在创建的约定类型定义单个方法Apply,其中包含不同的参数; 此方法是您对映射进行更改的方法.
...
起草的例子:
public class UtcConvention : IPropertyConvention
{
public void Apply(IPropertyInstance instance)
{
if (instance.Type.Name == "Date")
{
instance.CustomType<UtcDateTimeType>();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我们必须将其添加到配置中
FluentMappings
.Conventions.Add(new UtcConvention())
Run Code Online (Sandbox Code Playgroud)
嗨,感谢您的回答拉迪姆,
我必须对您的代码进行一些小的更改才能使其工作并支持可为空的DateTime?特性。
public class UtcConvention : IPropertyConvention {
public void Apply(IPropertyInstance instance) {
if (instance.Type.Name == "DateTime" || instance.Type.ToString().StartsWith("System.Nullable`1[[System.DateTime")) {
instance.CustomType<UtcDateTimeType>();
}
}
}
Run Code Online (Sandbox Code Playgroud)
也许这可能会帮助其他人寻找解决方案