Sequential GUID in Linq-to-Sql?

后端 未结 6 1886
忘掉有多难
忘掉有多难 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:55

    You can always call UuidCreateSequential; this is the 'old' guid generator (pre-2000-ish when MSFT changed it to the more random style guids we are used to today). They renamed the old UuidCreate to UuidCreateSequential, and put their new guid generator in a new implementation of UuidCreate. UuidCreateSequential is also what SQL Server uses in NewSequentialID(), and it is as unique as normal guids but with the benefit that they are sequential if you create a pile of them in a row in the same process.

    using System;
    using System.Runtime.InteropServices;
    
    namespace System
    {
        public static class GuidEx
        {
            [DllImport("rpcrt4.dll", SetLastError = true)]
            private static extern int UuidCreateSequential(out Guid guid);
            private const int RPC_S_OK = 0;
    
            /// 
            /// Generate a new sequential GUID. If UuidCreateSequential fails, it will fall back on standard random guids.
            /// 
            /// A GUID
            public static Guid NewSeqGuid()
            {
                Guid sequentialGuid;
                int hResult = UuidCreateSequential(out sequentialGuid);
                if (hResult == RPC_S_OK)
                {
                    return sequentialGuid;
                }
                else
                {
                    //couldn't create sequential guid, fall back on random guid
                    return Guid.NewGuid();
                }
            }
        }
    }
    

提交回复
热议问题