流利的NHibernate CheckProperty和日期

Chr*_*s C 5 unit-testing date fluent-nhibernate

我设置了一个NUnit测试:

new PersistenceSpecification<MyTable>(_session)
    .CheckProperty(c => c.ActionDate, DateTime.Now);
Run Code Online (Sandbox Code Playgroud)

当我通过NUnit运行测试时,我收到以下错误:

SomeNamespace.MapTest: 
System.ApplicationException : Expected '2/23/2010 11:08:38 AM' but got 
'2/23/2010 11:08:38 AM' for Property 'ActionDate'
Run Code Online (Sandbox Code Playgroud)

ActionDate字段是SQL 2008数据库中的日期时间字段.我使用自动映射并将ActionDate声明为C#中的DateTime属性.

如果我改变测试使用DateTime.Today测试通过.

我的问题是为什么测试失败了DateTime.Now?将日期保存到数据库时NHibernate是否会失去一些精确度,如果是这样,如何防止丢失?谢谢.

Gre*_*ose 6

由于sql server无法存储所有的毫秒数(但是在msdn中可以看到舍入为.003/.004/.007秒的增量),因此在将日期时间值传递给CheckProperty方法之前,应截断C#中的DateTime值.由于精度损失,从db中检索到的与DateTime.Now不同.

例如,如果您只需要精度秒,则可以截断毫秒,如SO问题的答案所示:如何截断.NET DateTime的毫秒数.
如果需要更高的精度,则应使用时间戳映射类型.

您可以使用扩展方法轻松截断毫秒:

public static class DateTimeExtension
{
  public static DateTime TruncateToSeconds(this DateTime source)
  {
    return new DateTime(source.Ticks - (source.Ticks%TimeSpan.TicksPerSecond), source.Kind);
  }
}
//<...>
new PersistenceSpecification<MyTable>(_session)
    .CheckProperty(c => c.ActionDate, DateTime.Now.TruncateToSeconds());
Run Code Online (Sandbox Code Playgroud)