Skip to content

Instantly share code, notes, and snippets.

@schourode
Created July 9, 2012 11:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schourode/3075912 to your computer and use it in GitHub Desktop.
Save schourode/3075912 to your computer and use it in GitHub Desktop.
NHibernate user type for storing sequential GUIDs as BINARY(16) with minimum fragmentation
using System;
using System.Data;
using NHibernate;
using NHibernate.SqlTypes;
using NHibernate.UserTypes;
public class BinaryGuidType : IUserType
{
private static readonly int[] ByteOrder = new[] { 10,11,12,13,14,15,8,9,6,7,4,5,0,1,2,3 };
private static readonly SqlType[] Types = new[] { new SqlType(DbType.Binary) };
public SqlType[] SqlTypes
{
get { return Types; }
}
public Type ReturnedType
{
get { return typeof(Guid); }
}
public new bool Equals(object x, object y)
{
return (x != null && x.Equals(y));
}
public int GetHashCode(object x)
{
return x.GetHashCode();
}
public object NullSafeGet(IDataReader rs, string[] names, object owner)
{
var bytes = (byte[]) NHibernateUtil.Binary.NullSafeGet(rs, names[0]);
if (bytes == null || bytes.Length == 0) return null;
var reorderedBytes = new byte[16];
for (var i = 0 ; i < 16; i++)
{
reorderedBytes[ByteOrder[i]] = bytes[i];
}
return new Guid(reorderedBytes);
}
public void NullSafeSet(IDbCommand cmd, object value, int index)
{
if (null != value)
{
var bytes = ((Guid) value).ToByteArray();
var reorderedBytes = new byte[16];
for (var i = 0; i < 16; i++)
{
reorderedBytes[i] = bytes[ByteOrder[i]];
}
NHibernateUtil.Binary.NullSafeSet(cmd, reorderedBytes, index);
}
else
{
NHibernateUtil.Binary.NullSafeSet(cmd, null, index);
}
}
public object DeepCopy(object value)
{
return value;
}
public bool IsMutable
{
get { return false; }
}
public object Replace(object original, object target, object owner)
{
return original;
}
public object Assemble(object cached, object owner)
{
return cached;
}
public object Disassemble(object value)
{
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment