下面的代码可以在NHibernate.Id.GuidCombGenerator类中找到。该算法基于将“随机”guid与DateTime结合起来创建顺序(梳理)guid。我有一对夫妇的关系,我已经标有线路问题* 1),* 2)所示:有关NHibernate的GuidCombGenerator的一些问题
private Guid GenerateComb()
{
byte[] guidArray = Guid.NewGuid().ToByteArray();
// *1)
DateTime baseDate = new DateTime(1900, 1, 1);
DateTime now = DateTime.Now;
// Get the days and milliseconds which will be used to build the byte string
TimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks);
TimeSpan msecs = now.TimeOfDay;
// *2)
// Convert to a byte array
// Note that SQL Server is accurate to 1/300th of a millisecond so we divide by 3.333333
byte[] daysArray = BitConverter.GetBytes(days.Days);
byte[] msecsArray = BitConverter.GetBytes((long) (msecs.TotalMilliseconds/3.333333));
// Reverse the bytes to match SQL Servers ordering
Array.Reverse(daysArray);
Array.Reverse(msecsArray);
// Copy the bytes into the guid
Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2);
Array.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4);
return new Guid(guidArray);
}
首先,对于* 1),那岂不是更好有更最近的日期作为baseDate,例如2000-01-01,为未来更多价值腾出空间?
关于* 2),为什么我们会关心SQL Server日期时间的准确性,当我们只对日期时间的字节感兴趣时,并且从不打算将值存储在SQL Server日期时间字段中?使用DateTime.Now提供的所有精度不是更好吗?
我想知道为什么它使用DateTime.Now而不是DateTime.UtcNow? 如果您在不同时区的服务器上创建GUID,则偏移量将会不同,并且GUID不会是连续的。 – MartinF 2010-05-24 16:53:18