LINQ To SQL Enum Support Example Using Discriminator Column and Inheritance Mapping

LINQ To SQL Enum Support Example Using Discriminator Column and Inheritance Mapping

by David Hayden ( Florida .NET C# SQL Server Developer ), Filed: LINQ To SQL Tutorials

 

In the last LINQ To SQL Post: LINQ To SQL Discriminator Column Example - Inheritance Mapping Tutorial, I could have easily changed the EmployeeType Property on the Employee Entity from int to an enum, called EmployeeType, and apparently LINQ To SQL will automatically take care of the conversion from int to the enum for me.

The EmployeeType Field in the database is int:

 

LINQ To SQL

 

but I can add an enum, called EmployeeType:

 

public enum EmployeeType : int
{
    HourlyEmployee = 0,
    SalariedEmployee = 1,
    CommissionedEmployee = 2
}

 

and change the Discriminator Property for Inheritance Mapping to the enum instead of int:

 

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

 

and all works fine. LINQ To SQL takes care of the mapping for me.

Ideally, however, you are not doing anything directly with the EmployeeType Property. You would create and save a Salaried Employee as follows:

 

using (HRDataContext dc = new HRDataContext())
{
    Employee empNew = new SalariedEmployee();
    empNew.Name = "Jane Doe";
    dc.Employees.Add(empNew);
    dc.SubmitChanges();
}

 

or something like that anyway. You may be hiding the creation of the proper employee type behind an EmployeeFactory, but you get the idea.

The direct enum support is nice.

LINQ To SQL Tutorials:

 

News Feed: David Hayden ( Florida .NET C# SQL Server Developer )

Filed: LINQ To SQL Tutorials

posted on Sunday, October 28, 2007 1:01 PM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices