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