Skip to content

Instantly share code, notes, and snippets.

@schotime
Created February 13, 2012 04:00
Show Gist options
  • Save schotime/1813516 to your computer and use it in GitHub Desktop.
Save schotime/1813516 to your computer and use it in GitHub Desktop.
Guid PK Petapoco
[TableName("Tests"), PrimaryKey("Id", autoIncrement = false)]
public class Test
{
public Test()
{
Id = GuidComb.NewGuid();
}
public Guid Id { get; set; }
}
public static class GuidComb
{
public static Guid NewGuid()
{
byte[] b = Guid.NewGuid().ToByteArray();
DateTime dateTime = new DateTime(1900, 1, 1);
DateTime now = DateTime.Now;
TimeSpan timeSpan = new TimeSpan(now.Ticks - dateTime.Ticks);
TimeSpan timeOfDay = now.TimeOfDay;
byte[] bytes1 = BitConverter.GetBytes(timeSpan.Days);
byte[] bytes2 = BitConverter.GetBytes((long)(timeOfDay.TotalMilliseconds / 3.333333));
Array.Reverse(bytes1);
Array.Reverse(bytes2);
Array.Copy(bytes1, bytes1.Length - 2, b, b.Length - 6, 2);
Array.Copy(bytes2, bytes2.Length - 4, b, b.Length - 4, 4);
return new Guid(b);
}
}
var db = new Database("conn");
var test = new Test();
db.Insert(test);
var guid = test.Id;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment