LINQ To SQL Discriminator Column Example - Inheritance Mapping Tutorial

LINQ To SQL Discriminator Column Example - Inheritance Mapping Tutorial

by David Hayden ( Microsoft MVP C# ), Filed: LINQ To SQL

 

I am developing my second application using LINQ To SQL and getting much more comfortable using it for real-world development. Not bad given that LINQ To SQL and Visual Studio 2008 have not yet been released.

For the first time, I used the single table inheritance feature of LINQ To SQL. With LINQ To SQL you can specify a Discriminator Column and Inheritance Mapping that specifies the type to be created in a hierarchy. Let's say we have an abstract Employee Class that maps to an Employees Table in the database with employees being an hourly employee, salaried employee, or commissioned-based employee:

 

LINQ To SQL Discriminator Column

 

The EmployeeType Column in the Employees Tables specifies the type of employee and is the Discriminator Column:

 

IsDiscriminator Column

 

The EmployeeType Property on the abstract Employee Class is marked as the Descriminator Column using the IsDiscriminator Property on the LINQ To SQL Column Attribute:

 

[Column(Storage = "_EmployeeType",
    DbType = "Int NOT NULL",
    IsDiscriminator = true)]
public int EmployeeType
{
    // ...
}

 

The Employee Class itself has InheritanceMapping Attributes that map EmployeeType Values to Types:

 

[Table(Name="dbo.Employees")]
[InheritanceMapping(Code = 0,
    Type = typeof(HourlyEmployee), IsDefault = true)]
[InheritanceMapping(Code = 1,
    Type = typeof(SalariedEmployee))]
[InheritanceMapping(Code = 2,
    Type = typeof(CommissionedEmployee))]
public abstract partial class Employee : ...

 

The InheritanceMapping Attributes above specify:

  • EmployeeType = 0: Create HourlyEmployee Class
  • EmployeeType = 1: Create SalariedEmployee Class
  • EmployeeType = 2: Create CommissionedEmployee Class

 

Now when we requests all the employees in the Employee Table, the actual type created depends on the value stored in the EmployeeType Column:

 

using (HRDataContext dc = new HRDataContext())
{
    foreach (Employee emp in dc.Employees)
        Console.WriteLine(emp.GetType().Name);
}

 

The LINQ To SQL Discriminator Functionality for inheritance mapping in a single table is a nice feature and proved useful in my current application.

 

LINQ To SQL Tutorials:

News Feed: David Hayden ( Microsoft MVP C# ), Filed: LINQ To SQL

 

posted on Friday, October 26, 2007 3:14 PM

My Links

Post Categories

Article Categories

Archives

Loose-Leaf Tea