Skip to content

Instantly share code, notes, and snippets.

@yemrekeskin
Created November 8, 2013 14:10
Show Gist options
  • Save yemrekeskin/7371557 to your computer and use it in GitHub Desktop.
Save yemrekeskin/7371557 to your computer and use it in GitHub Desktop.
Entity Designing
/// <summary>
/// Generates a sequential guid
/// Based on http://stackoverflow.com/questions/665417/sequential-guid-in-linq-to-sql
/// </summary>
/// <returns></returns>
public class GuidGenerator
{
public static Guid Generate()
{
var destinationArray = Guid.NewGuid().ToByteArray();
var time = new DateTime(1900, 1, 1);
var now = DateTime.UtcNow;
var ticksSince1900 = new TimeSpan(now.Ticks - time.Ticks);
var bytesFromClockTicks = BitConverter.GetBytes(ticksSince1900.Days);
var timeOfDay = now.TimeOfDay;
var bytesFromMilliseconds = BitConverter.GetBytes((long)(timeOfDay.TotalMilliseconds / 3.333333));
Array.Reverse(bytesFromClockTicks);
Array.Reverse(bytesFromMilliseconds);
Array.Copy(bytesFromClockTicks, bytesFromClockTicks.Length - 2, destinationArray, destinationArray.Length - 6, 2);
Array.Copy(bytesFromMilliseconds, bytesFromMilliseconds.Length - 4, destinationArray, destinationArray.Length - 4, 4);
return new Guid(destinationArray);
}
}
public interface IEntity { }
public abstract class Entity
: IEntity
{
public Entity()
{
this.UniqueId = GuidGenerator.Generate();
}
public Guid UniqueId { get; set; }
public int Id { get; set; }
public DateTime CreateDate { get; set; }
public string CreateBy { get; set; }
public DateTime UpdateDate { get; set; }
public string UpdateBy { get; set; }
public bool IsActive { get; set; }
}
public class Product
: Entity
{
}
// test
class Program
{
static void Main(string[] args)
{
Product p = new Product();
Console.WriteLine(p.UniqueId);
Product d = new Product();
Console.WriteLine(d.UniqueId);
Console.ReadLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment