How to implement Guid.Comb on SQL Server with Entity Framework Code First

Read this if you don’t know the “why” behind Guid.Comb. In a nutshell. We want to uniquely identify records and don’t want PK collisions across database instances. Using Guid as a PK used to be taboo. Now (circa 2002) it’s acceptable with Guid.Comb. It generates Guids in a semi-sequential order to limit page splits. This post is a combination of this and this. Here’s a good post on how to do Guid.Comb with NHibernate.

Download Latest version from GitHub

What I’m using:

  1. EF 6 beta3 – Though you could probably use EF5 without issue
  2. VS2012 – Express should work
  3. SQL Express
  4. Nuget

1. Create a new Console App called GuidComb

2. Open Package Manager Console and run the following:

PM> Install-Package EntityFramework -Pre

3. Add this code to your app:

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace GuidComb
{
class Program
{
static void Main(string[] args)
{
using (var db = new ItemContext())
{
for (var i = 0; i < 10; i++)
db.Items.Add(new Item());
db.SaveChanges();
}
using (var db = new ItemContext())
{
foreach (var item in db.Items)
Console.WriteLine(item.Id);
}
Console.ReadKey();
}
}
public class Item
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
}
public class ItemContext : DbContext
{
public DbSet<Item> Items { get; set; }
}
}

4. Run the following in Package Manager Console

PM> Enable-Migrations

5. Run the following in Package Manager Console

PM> Add-Migration Comb

6. Open the /Migrations/[Timestamp]_Comb.cs that was created by the Add-Migration command and add defaultValueSql: “newsequentialid()” to the Item table Column builder.

namespace GuidComb.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Comb : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Items",
c => new
{
Id = c.Guid(nullable: false, identity: true, defaultValueSql: "newsequentialid()"),
})
.PrimaryKey(t => t.Id);
}
public override void Down()
{
DropTable("dbo.Items");
}
}
}

7. Hit F5 and you should see this:

As you can see the Guid are being generated sequentially.

Download Latest version from GitHub

Share