0

我构建了一个 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)。我不知道我做错了什么;有人能指出我正确的方向吗?

4

1 回答 1

0

好的,问题与实现无关IUserType;我将我的 POCO 定义为DateTime,不是Nullable<DateTime>,所以它们默认为DateTime.MinValue.

一旦我改变了这一点,一切都完全按照我的意愿工作。

于 2012-09-08T20:50:01.713 回答