我构建了一个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();
数据库的记录值(PostgreSQL)获得-infinty
。我不知道我做错了什么;有人能指出我正确的方向吗?
答案 0 :(得分:0)
好的,问题与IUserType
实施无关;我将我的POCO定义为DateTime
,而不是Nullable<DateTime>
,因此它们默认为DateTime.MinValue
。
一旦我改变了,一切都按照我想要的方式运作。