2010-05-20 24 views
14

我使用流利Nhibernate和Nhibernate爲我目前的項目。我需要將時間記錄到毫秒。我爲我的映射流利Nhiberhate和失蹤毫秒

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

我genertaed hbm.xml文件和線如下:

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

我已閱讀,這是固定的,但在數據庫中的記錄不有毫秒。有沒有人解決了這個問題。我也試過CustomSqlType。

謝謝

+2

是類型(數據庫)的時間戳列? – AlexCuse 2010-05-20 13:30:16

+0

此外,您已有的數據已被截斷,並且該信息已丟失。 – Jaguar 2010-05-24 14:15:37

+0

我也想知道哪個DB正在使用。例如,SQLite不存儲毫秒,並且需要解決方法。 – 2012-03-16 17:56:06

回答

13

我們使用與您相同的方法,它會正確存儲毫秒。如果你並不總是那樣做,儘管你的舊記錄會失去毫秒。

假設你想存儲毫秒爲所有日期時間字段,你可以使用一個約定:

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(); 
+0

任何想法,如果這可以在配置中完成,即。 'Fluently.Configure()。Conventions.Add(...)'? – 2012-09-06 09:37:19

+1

var factory = Fluently.Configure() .Mappings(m => m.FluentMappings.Conventions.Add(new TimestampConvention())) .BuildSessionFactory(); – daanl 2012-09-07 08:06:57

+0

@AshBurlaczenko另一個如何將約定添加到配置的例子是'var sessionFactory = Fluently.Configure(rawConfig).Database(PersistenceConfigurer).Mappings(m => m.FluentMappings.AddFromAssembly(typeof(OurPropertyConventions).Assembly)。 Conventions.AddFromAssemblyOf ());' – Manfred 2015-11-29 02:41:23

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(); 

我不知道爲什麼,雖然:/

+0

對我來說CustomType(「timestamp」)工作但CustomType(「Timestamp」)沒有 – AdrianCogiel 2015-05-26 13:19:16

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(); 
您正在使用的數據庫,什麼