Thursday, December 4, 2008

Single Table Inheritance With LINQ

For a while now I've been using LINQ in my ASP.NET applications and it has been a huge time saver. Having used nHibernate prior to this, the prospect of not having to deal with config files was a double bonus. One thing I do miss from nHibernate, however is the ability to add a simple Where clause in the class definition. For example, I regularly use a deleted flag in tables so as to avoid doing 'hard' deletes. In the nHibernate world, in order to exclude deleted records the config file would use something like this:
<class name="Core.ELSField, Core" table="dbo.tblFields" Where="fDeleted=0">

I've yet to find anything in the LINQ world that equates to this so I'm left including 'where !deleted' in all my queries. Oh well.

Inheritance in nHibernate is handled through discriminator columns and looks like this:

<class name="IPayment" table="PAYMENT">
<id name="Id" type="Int64" column="PAYMENT_ID">
<generator class="native"/>
<discriminator column="PAYMENT_TYPE" type="String"/>
<property name="Amount" column="AMOUNT"/>
<subclass name="CreditCardPayment" discriminator-value="CREDIT">


For the longest time, I was coding the equivalent LINQ version by hand. Little did I know that the O/R designer in Visual Studio handles this. MSDN provides a very nice example which you should be able to apply to your own situation. Hopefully you will find it as useful as I did.