2009-07-21 27 views
1

我有一个带有datetime字段的MySql数据库中的表。这被映射到我的域对象在hbm.xml文件,类似于以下属性:使用NHibernate的MySql数据库中的域对象中的DateTime分辨率

<property name="StartDate" column="datStartDate" not-null="true" type="datetime"/>

这一切工作正常,但MySQL不存储日期时间字段的毫秒部分。不过,我并不介意将域对象更新为具有存储在数据库中的确切值。我希望能够在我用于保存域对象的同一会话中执行此操作。

这可能吗?

回答

0

一个简单的方法是做session.Refresh(实体),但是这会导致额外的查询。

在Interceptor中工作,看起来很重。

http://www.nhforge.org/doc/nh/en/index.html#objectstate-interceptors(11.1)

你想要的东西,如:

public override bool OnFlushDirty(object entity, 
            object id, 
        object[] currentState, 
        object[] previousState, 
        string[] propertyNames, 
        IType[] types) 
{ 
    if(entity is DomainObjectICareAbout) 
     for (int i=0; i < propertyNames.Length; i++) { 
      if (currentState[i] is DateTime) { 
       DateTime dt = (DateTime)currentState[i]; 
       dt = dt.AddMilliseconds(-1 * dt.Millisecond); 
       return true; 
      } 
     } 
    } 
    return false; 
} 

同类的事情的OnSave()。

在Custom IUserType中这样做可能会更好,但我不确定用户类型是否暴露了这样做的能力?

像一个IUserType:

public void NullSafeSet(System.Data.IDbCommand cmd, object value, int index) 
{ 
    DateTime dt = (DateTime)value; 
    dt = dt.AddMilliseconds(-1 * dt.Millisecond); 
    NHibernateUtil.DateTime.NullSafeSet(cmd, dt, index); 
} 

我不知道......我不知道最好的答案。只是给出想法。可能有更好的方法!

+0

我想我现在要使用session.Refresh,即使它再次击中数据库。这已经证明是有用的:我发现我没有在连接字符串中设置字符集,所以我丢失了Unicode字符;)。 – Andrew 2009-07-21 14:17:53

+0

嗯,重新读你的问题(有关保持同一会话的部分),它看起来像Session.Refresh()是正确的答案。 – anonymous 2009-07-21 15:15:30