I'd like one of my entities to have a one-to-one relationship with a class hierarchy. Think of it like a Strategy pattern, where each strategy needs different parameters to be persisted. I tried using a combination of OneToOne
and JoinedBase
/JoinedKey
, but I've come across a problem.
With this combination, the primary key of the main entity also appears as the primary key of the table representing the root class in the hierarchy, and as the primary key of the subclass:
Order --------------- TaxCalculator
([PrimaryKey]Id = 1234) ([PrimaryKey(PrimaryKeyType.Foreign)]OrderId = 1234)
^
|
|
UkTaxCalculator
([JoinedKey]UkTaxCalculatorId = 1234)
I can persist this fine, but then I can't change which subclass of TaxCalculator
I have. When I do something like:
order.TaxCalculator = new OverseasTaxCalculator(order);
then try to flush, then ActiveRecord/NHibernate (understandably) gets unhappy that there are now two TaxCalculators
with Id = 1234
.
I can get around this by replacing the OneToOne
with a HasMany
/BelongsTo
, and hiding the multiplicity from users of the Order
object, but I'm interested to know if it's possible to do this with OneToOne
.
There's a full code example on github. This code throws an exception when the second SessionScope
is disposed. If you clone the project, it should run out-of-the-box.