流利的Nhiberhate和缺少毫秒

时间:2010-05-20 13:20:43

标签: nhibernate fluent-nhibernate fluent-nhibernate-mapping

我正在使用Fluent Nhibernate和Nhibernate来完成我当前的项目。我需要将时间记录到毫秒。我有这个用于我的映射

            Map(x => x.SystemDateTime)
            .CustomType("Timestamp")
            .Not.Nullable();

我创建了hbm.xml文件,该行如下:

<property name="SystemDateTime" type="Timestamp">
  <column name="SystemDateTime" not-null="true" />
</property>

我已经读过这是修复,但数据库中的记录没有毫秒。有谁解决了这个问题。我也尝试过CustomSqlType。

由于

3 个答案:

答案 0 :(得分:13)

我们使用与您相同的方法,它可以正确存储毫秒数。如果你并不总是那样做,虽然你的旧唱片会丢失毫秒。

假设您要为所有DateTime字段存储毫秒,可以使用约定:

public class OurPropertyConventions : IPropertyConvention
{
    public void Apply(IPropertyInstance instance)
    {
        Type type = instance.Property.PropertyType;
        if (type == typeof(DateTime) || type == typeof(DateTime?))
            instance.CustomType("Timestamp");
    }
}

您的映射现在可以是:

Map(x => x.SystemDateTime).Not.Nullable();

答案 1 :(得分:2)

重新审视此事,因为之前的答案稍有不完整。

假设您希望以完整详细信息和毫秒精度存储所有DateTime字段,请使用TIMESTAMP(6) WITH TIME ZONE作为SQL列类型。你需要一个FluentNHibernate的属性约定:

using System;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.AcceptanceCriteria;
using FluentNHibernate.Conventions.Inspections;
using FluentNHibernate.Conventions.Instances;

internal class DateTimeMapsToTimestampConvention
    : IPropertyConvention, IPropertyConventionAcceptance
{
    public void Apply(IPropertyInstance instance)
    {
        instance.CustomType<NHibernate.Type.TimestampType>();
    }

    public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
    {
        criteria.Expect(x => x.Type == typeof(DateTime)
            || x.Type == typeof(DateTime?));
    }
}

然后,将此约定添加到流畅的配置会话工厂构建代码中:

var factory =  Fluently.Configure().Mappings(
  m => assemblies.ForEach(
    assembly => m.FluentMappings.AddFromAssembly(assembly)
                .Conventions.Add(new DateTimeMapsToTimestampConvention())))
            .BuildSessionFactory();

答案 2 :(得分:1)

这对我不起作用:

Map(x => x.DateCreated).Column("DATE_CREATED").CustomSqlType("TIMESTAMP(6) WITH TIME ZONE").Not.Nullable();

虽然这样做了:

Map(x => x.DateCreated).Column("DATE_CREATED").CustomType("timestamp").CustomSqlType("TIMESTAMP(6) WITH TIME ZONE").Not.Nullable();

我不知道为什么,但是:/