Tuesday, April 3, 2012

Table per subclass using a discriminator with mapping-by-code

Recently xanatos in a comment to one of my mapping-by-code series post asked how to implement hybrid-mode inheritance with both table per subclass and discriminator columns using mapping-by-code. I think this scenario is quite exotic (why do we need a discriminator column if we have separate tables?), but the documentation explicitly mentions this possibility, so it should be possible with mapping-by-code, too.

Here is the expected XML mapping fragment:

<class name="Payment" table="PAYMENT">
<id name="Id" type="Int64" column="PAYMENT_ID">
<generator class="native"/>
</id>
<discriminator column="PAYMENT_TYPE" type="string"/>
<property name="Amount" column="AMOUNT"/>
...
<subclass name="CreditCardPayment" discriminator-value="CREDIT">
<join table="CREDIT_PAYMENT">
<key column="PAYMENT_ID"/>
<property name="CreditCardType" column="CCTYPE"/>
...
</join>
</subclass>
</class>

And here is how to do it in mapping-by-code:

public class PaymentMap : ClassMapping<Payment>
{
public PaymentMap()
{
Id(x => x.Id, m => m.Generator(Generators.Native));
Discriminator(d => d.Column("PaymentType"));
Property(x => x.Amount);
}
}

public class CreditCardPaymentMap : SubclassMapping<CreditCardPayment>
{
public CreditCardPaymentMap()
{
DiscriminatorValue("CREDIT");
Join("CreditPayment", j => j.Property(x => x.CreditCardType));
}
}

I'm impressed again how easily XML mapping can be translated to mapping-by-code syntax.

3 comments:

  1. What about an example in Fluent Nhibernate?

    ReplyDelete
  2. I agree: what about an example in Fluent Nhibernate?
    Regards

    ReplyDelete
    Replies
    1. Hey, this post was specifically about mapping-by-code, I have not intended to write about Fluent NHibernate here at all. I haven't tried it in FNH.

      Delete

Note: Only a member of this blog may post a comment.