顺序的GUID的LINQ到SQL?顺序、GUID、SQL、LINQ

2023-09-02 01:29:15 作者:мё琓嗰性ˇ

我刚刚读了blog帖子有关NHibernate的创建从系统时间(Guid.Comb)一个GUID的能力,从而避免数据库碎片一个良好的数额。你可以把它等同于SQL Server的顺序号的客户端。

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 it the client-side equivalent to the SQL Server Sequential ID.

有没有一种方法,我可以用我的LINQ到SQL项目类似的策略(通过生成的GUID在code)?

Is there a way I could use a similar strategy in my Linq-to-Sql project (by generating the Guid in code)?

推荐答案

梳生成以下方式:

DECLARE @aGuid UNIQUEIDENTIFIER

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

哪个转录成C#是这样的:

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 );
	}