Pierre Greborio.NET

Talking about .NET world

Identity field

The identity in object orientation is the memory object address (its pointer). In a database it is the primary key. Martin Fowler suggests to save the identity of the database table (primary key) on the object field/s.

Ok, which key type are we using ? Is it an integer, uniqueidentifier, varchar, char or whatelse ? We can define e generic type mapped to any type we need, more or less as following:

public class Key<T>
{
 private T _value;

 public Key() { }

 public Key(T value)
 {
  if (value == null)
   _value = default(T);
  else
   _value = value;
 }

 public override string ToString()
 {
  return (_value == null) ? "" : _value.ToString();
 }

 public static implicit operator Key<T>(T value)
 {
  return new Key<T>(value);
 }

 public static implicit operator T(Key<T> value)
 {
  if (value == null)
   return default(T);
  else
   return value._value;
 }
}

Obviously, the above type doesn't consider primary keys composed by multiple columns. In that case we could implement an IList<Key> or something like that. 

Comments

Guy S. said:

Yep, a generic key will be generic if it will be implemened using IList to enable compound key and a set of methods to menipulate it - as u suggested
# November 22, 2004 8:17 AM