Wednesday, November 26, 2008

Entity Framework Inheritance

Click For Larger Image

After a couple of tries, I've got inheritance working and it's pretty neat. Here's the short version.

First, generate a model. In this case I created a small model with Facility, Affiliation, and Organization. I should say Affiliation is a ternary association class and working with it in traditional code has been a lot of trouble.

Second add a subtype class. In this case, I created a class called FacilityOwner, which is a subset of the Affiliation table. (In EF terminology, this is called Table-per-Hierarchy). The discriminator is AffiliationTypeID and was put in as a condition when I mapped the entity to the Affiliation table.

Once you understand how it's supposed to work, using subclasses is actually simple. To make a query that returns facility owners, you need to use the OfType<> operator of the base class.

In my case, this is Affiliation, so a query that returns all facility owners looks like this:

var facilityOwners = from foList
in ctx.Affiliation.OfType()
select foList;