Is there a .NET equivalent to SQL Server's newsequentialid()

前端 未结 10 2187
孤城傲影
孤城傲影 2020-12-02 10:47

We use GUIDs for primary key, which you know is clustered by default.

When inserting a new row into a table it is inserted at a random page in the table (because GUID

10条回答
  •  难免孤独
    2020-12-02 11:08

    Update 2018: Also check my other answer

    This is how NHibernate generate sequantial IDs:

    NHibernate.Id.GuidCombGenerator

    /// 
    /// Generate a new  using the comb algorithm.
    /// 
    private Guid GenerateComb()
    {
        byte[] guidArray = Guid.NewGuid().ToByteArray();
    
        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;
    
        // 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);
    }
    

提交回复
热议问题