Single Table Inheritance using LINQ

My most recent venture in technical world has been learning MS technologies and eventually O/RM using LINQ. Language Integrated Query or LINQ is a Microsoft feature that allows you to map your relational database tables to objects. I will talk about mapping a single table to a class hierarchy – Single Table Inheritance – using LINQ.

LINQ features are located in System.Linq, System.Data.Linq, and System.Data.Linq.Mapping namespaces. It’s mapping attribute [InheritanceMapping] does all the job for you.

Let us write a base class called Node and map it to a table in database using the TableAttribute.

  [Table(Name = "MST_EQUIP")]
[InheritanceMapping(Code = "SOURCE", Type = typeof(Source)]
public class Node
   {
       [Column(Name = "EQUIP_TYPE", IsDiscriminator = true,IsPrimaryKey=true)]
       public string NodeType;
  }

The Attribute, Column maps the field, NodeType to a column, EQUIP_TYPE, in database. The parameter IsDiscriminator identifies whether this column is the basis of inheritance.

In the Attribute, InheritanceMapping the parameter Code identifies the value in the Discriminating column which results in child class for the node. The Type parameter identifies the class.

In simple English, if the column EQUIP_TYPE of the table MST_EQUIP has the string “SOURCE” in it,  LINQ will create an Object of type Source for you. The class Source, of course, inherits the class Node.

That’s cool, isn’t it ?


About this entry