This project is read-only.

Mapping Inheritance

Linq to Sql support mapping inheritance hierarchies and Fluent Linq to Sql allows you to do the same.

For example, imagine you have a Customer object and a PreferredCustomer object that inherits from Customer:

public class Customer {
	public int Id { get; set; }
	public string Name { get; set; }
	public int CustomerType { get; set; }

public class PreferredCustomer : Customer {
	public double? Discount { get; set; }

When mapping inheritance hierarchies in Linq to Sql, all the fields for both classes will reside in the same table (Customer). A discriminator column can be used to indicate whether a row in the table is a Customer or a PreferredCustomer. In this example we will use the CustomerType field for this. Customers will have a CustomerType of 0 and PreferredCustomers will have a CustomerType of 1.

To map this, you would call the DiscriminateOnProperty method inside your CustomerMapping:

public class CustomerMapping : Mapping<Customer> {
   public CustomerMapping() {
     Identity(x => x.Id);
     Map(x => x.Name);
     DiscriminateOnProperty(x => x.CustomerType)
         .SubClass<PreferredCustomer>(1, preferredCustomer => {
             preferredCustomer.Map(x => x.Discount);

In this example we specify that the CustomerType is the discriminator column, the base class (Customer) will have a CustomerType of 0, the subclass (PreferredCustomer) will have a CustomerType of 1 and that the PreferredCustomer has some additional columns not available on the base class (Discount). If you have multiple subclasses, you can call .SubClass<T> multiple times.

Last edited Sep 6, 2009 at 3:02 PM by JeremyS, version 2


No comments yet.