LINQ to SQL Single Table Inheritance Example

With LINQ to SQL we can get model inheritance with filtered mapping, called Single Table Inheritance. We do this by applying a discriminator value to the derived classes. By mapping this value LINQ to SQL knows to instantiate the appropriate base or derived class.

In this example we have a Car base class with the derived types SportsCar and ElectricHybridCar. All cars have a Brand name, but the SportsCar and ElectricHybridCar have some specific properties. The Car base has the discriminator value we mentioned above. It’s a simple character field.

LINQ To SQL Cars Class Hierarchy

We set the discriminator value by configuring the inheritance properties. In this case we clicked the arrow between Car and SportsCar and set the Derived Class Discriminator Value to “S” for SportsCar and the Base Class Dicriminator to “C” for Car. In the Discriminator Property we select the name of the column in our table we use for storing the discriminator values. We do the same for the ElectricHybricCar inheritance properties, this time with the discriminator value “E”.

SportsCar Inheritance Properties Discriminator

We use only one Car table in SQL server to store all the properties of our cars.

Car SQL Single Table

To test if LINQ to SQL actually gives us different types of Cars, SportsCars and ElectricHybridCars back based on the discriminator, we build a simple console application. Iterating through the complete list we print out the specific type of car to the console.

using System;
using System.Linq;
using Remondo.Database;
 
namespace CarsLinqToSqlInheritance
{
    internal class Program
    {
        private static void Main()
        {
            var dataContext =
                new CarsDataContext();
 
            IQueryable<Car> cars =
                dataContext.Cars;
 
            foreach (Car car in cars)
            {
                Console.WriteLine("{0}",
                    car.GetType().FullName);
            }
 
            Console.ReadKey();
        }
    }
}

And indeed… ;-)

LINQ To SQL Single Table Inheritance Console

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>