我构建了一个 IUserType 类来默认记录上的 UTC 创建时间戳。我以为我正确地实现了它,但它对数据库没有任何保留。有人可以告诉我我做错了什么吗?该类类似于:
public class UTCTimeStamp : IUserType
{
public object Assemble(object cached, object owner)
{
return DeepCopy(cached);
}
public object DeepCopy(object value)
{
var orig = value as Nullable<DateTime>;
if (orig == null) return null;
var newVal = new DateTime(
((DateTime)orig).Ticks);
return newVal;
}
public object Disassemble(object value)
{
return DeepCopy(value);
}
public bool Equals(object x, object y)
{
if (ReferenceEquals(x, y)) return true;
if (x == null || y == null) return false;
return x.Equals(y);
}
public int GetHashCode(object x)
{
if (x == null)
{
throw new ArgumentNullException("Argument cannot be null.");
}
return x.GetHashCode();
}
public bool IsMutable
{
get { return false; }
}
public object NullSafeGet(System.Data.IDataReader rs, string[] names, object owner)
{
var timestamp = NHibernate.NHibernateUtil.DateTime.NullSafeGet(rs, names[0]);
if (timestamp != null && timestamp is DateTime)
{
return (DateTime)timestamp;
}
return null;
}
public void NullSafeSet(System.Data.IDbCommand cmd, object value, int index)
{
if (value == null || !(value is Nullable<DateTime>))
{
NHibernate.NHibernateUtil.DateTime.NullSafeSet(cmd, DateTime.UtcNow, index);
return;
}
NHibernate.NHibernateUtil.DateTime.NullSafeSet(
cmd, value, index);
}
public object Replace(object original, object target, object owner)
{
return original;
}
public Type ReturnedType
{
get
{
return typeof(Nullable<DateTime>);
}
}
public NHibernate.SqlTypes.SqlType[] SqlTypes
{
get
{
return new[] { new SqlType(System.Data.DbType.DateTime) };
}
}
}
映射如下所示:
Map(x => x.CreatedTimestamp)
.Column("CreatedTimeStamp")
.CustomType<UTCTimeStamp>()
.Not.Nullable();
数据库正在获取-infinty
记录的价值(PostgreSQL)。我不知道我做错了什么;有人能指出我正确的方向吗?