views:

250

answers:

1

NHibernate doesn't require too much decoration of POCOs, but having to put surrogate keys in my domain objects makes me feel a bit ill. Call me over-zealous - I'd prefer 'ideologically consistent' - but my domain objects should surely work with natural keys and not have to resort to surrogates.

I don't mind using surrogates in my database, but I don't really want to tamper with my working domain model. How do I circumvent this problem?

Do I subclass the domain classes with composite keys, adapting them so that NH can use a surrogate key but my domain is none-the-wiser, seeing only the superclass?

class DomainClass
{
     private ParentClass1 _p1; // These two form a composite key
     private ParentClass2 _p2; //
     private int _i;   

     public int SomeProp
     {
         get { return _i; }
     }
}

class NHDomainClass : DomainClass
{
    private long _surrogateKey
    private DomainClass _d;

    public int SomeProp
    {
         get { return  _d.SomeProp; }
    }
}

In this (hasty, contrived) example, NH sees NHDomainClass and can use the surrogate but, because it adapts DomainClass, it can still be used as a viable DomainClass in model-specific code. I'm fairly sure this will work, just want to make sure that I'm not missing some obvious simpler method which would achieve the same thing in a fraction of the time.

Thanks.

+2  A: 

I'm not sure that you'd want to subclass your regular domain objects just to add the surrogate key. You would end up with a lot of code noise in your queries because you would need to use the type name that Nhibernate is familiar with like so.

session.CreateCriteria(typeof(NHDomainClass));

Instead I would probably settle for hiding the surrogate key (I prefer guids for ease with replication and merging) as a private field or protected property inside your regular domain classes.

Danielg