Sequential GUID in Linq-to-Sql?

后端 未结 6 1884
忘掉有多难
忘掉有多难 2020-11-28 23:39

I just read a blog post about NHibernate\'s ability to create a GUID from the system time (Guid.Comb), thus avoiding a good amount of database fragmentation. You could call

6条回答
  •  佛祖请我去吃肉
    2020-11-28 23:51

    COMBs are generated the following way:

    DECLARE @aGuid UNIQUEIDENTIFIER
    
    SET @aGuid = CAST(CAST(NEWID() AS BINARY(10)) + CAST(GETDATE() AS BINARY(6)) AS UNIQUEIDENTIFIER)
    

    Which transcribed into C# would look like this:

        public static unsafe Guid CombGuid()
        {
            Guid guid = Guid.NewGuid();
            byte[] bytes = guid.ToByteArray();
            long ticks = DateTime.Now.Ticks;
            fixed( byte* pByte = bytes )
            {
                int*    pFirst  = (int *)(pByte + 10);
                short* pNext    = (short*)(pByte + 14);
                *pFirst = (int)(ticks & 0xFFFFFF00);
                *pNext  = (short)ticks;
            }
    
            return new Guid( bytes );
        }
    

提交回复
热议问题