Pierre Greborio.NET

Talking about .NET world

Composite key

Two days ago I wrote about the key identity for OO-Table mapping. The sample code works only for a single key field in the table, but it doesn't for a composite key values.

There are several solutions for this problem and probably, the simples one is to create a CompositeKey calss wich is a simple list of Key objects. In order to have a generic container of keys identified by an identifier (field name ?) we have to inherit the Key class from an interface (empty):

public interface IKey { }

public class Key<T> : IKey
{
  // ....
}

Then, the CompositeKey can contains an array of keys as following:

class CompositeKey : Dictionary<string, IKey>
{
    public IKey GetKeyByIdentity(string identifier)
    {
        return this[identifier];
    }

    // ...
}

[Question: can you suggest a better name than identifier ?]

In order to have a more usable container we can add some convenience methods, such as:

public void Add(string identifier, Guid code)
{
    this.Add(identifier, (new Key<Guid>(code)) as IKey);
}

Another idea is to have several Key fields into the domain object.

 

Comments

Udi Dahan - The Software Simplist said:

I'd suggest that CompositeKey implement IKey.
# November 29, 2004 5:54 AM