Basis of LINQ to SQL: Entity Inheritance


The goal of this post is to illustrate the inheritance concept in LINQ to SQL.

We use inheritance when we want to map a set of classes derived from the same base class with the same relational table.

Contact will be our Base Class:

[Table(Name = "Contact")]
[InheritanceMapping(Code = "Employee", Type = typeof (EmployeeContact), IsDefault = true)]
[InheritanceMapping(Code = "Company", Type = typeof(CompanyContact))]


public class Contact
{
     [Column(IsDbGenerated=true,IsPrimaryKey=true)]
     public Guid Id;

     [Column]
     public string Name;

     [Column(IsDiscriminator = true)]
     public string EntityType;
}

The InheritanceMapping attribute specify the corresponding derived class which will be identified by a special discriminator column. The Code parameter défines the value and the Type parameter défines the corresponding derived type. We have to had a field to store the discriminator value (EntityType in our sample). This field is mapped with a column which will have the value of the corresponing type.

CompanyContact and EmployeeContact derive from Contact

public class CompanyContact: Contact
{
     [Column]
     public string SubName;
}


public class EmployeeContact:Contact
{
     [Column]
     public string WebSite;
}

Those derived classes don’t need to have the table attribute. Because they derived from Contact class, they are mapped with same table than Contact.

The following class represents our DataContext:

public class MyDataContext : DataContext
{
     public Table<Contact> Contacts;
     public MyDataContext(string connection) : base(connection)
}

 


This script creates the correponding DataBase with two records:


image

We can check the result in the SQL Server :

clip_image002[4]

Skip to main content