Mapping System.Net.IPAddress as Nvarchar With NHibernate

Without further ado, here’s an implementation of IUserType, which allows writing and reading instances of IPAddress from a nvarchar column.

The class inherits from the abstract UserType class described in my previous post

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class IpAddressAsString : UserType
{
  #region Overrides of UserType

  public override object NullSafeGet(IDataReader rs, string[] names, object owner)
  {
    object obj = NHibernateUtil.String.NullSafeGet(rs, names);
    if (obj == null)
    {
      return null;
    }
    return IPAddress.Parse(obj.ToString());
  }

  public override void NullSafeSet(IDbCommand cmd, object value, int index)
  {
    Check.Require(cmd != null);
    if (value == null)
    {
      ((IDataParameter)cmd.Parameters[index]).Value = DBNull.Value;
    }
    else
    {
      ((IDataParameter)cmd.Parameters[index]).Value = value.ToString();
    }
  }

  public override SqlType[] SqlTypes
  {
    get { return new SqlType[] { SqlTypeFactory.GetString(15) }; }
  }

  public override Type ReturnedType
  {
    get { return typeof(IPAddress); }
  }

  #endregion
}

I’d recently used this class to stored failed and successful logon attempts. Again it’s just too simple but I’m happy to share.