Export (0) Print
Expand All

How to: Map Inheritance Hierarchies

To implement inheritance mapping in LINQ, you must specify the attributes and attribute properties on the root class of the inheritance hierarchy as described in the following steps. Developers using Visual Studio can use the Object Relational Designer to map inheritance hierarchies. How to: Configure Inheritance by Using the O/R Designer
How to: Configure Inheritance by Using the O/R Designer

Note Note

No special attributes or properties are required on the subclasses. Note especially that subclasses do not have the TableAttribute attribute.

To map an inheritance hierarchy

  1. Add the TableAttribute attribute to the root class.

  2. Also to the root class, add an InheritanceMappingAttribute attribute for each class in the hierarchy structure.

  3. For each InheritanceMappingAttribute attribute, define a Code property.

    This property holds a value that appears in the database table in the IsDiscriminator column to indicate which class or subclass this row of data belongs to.

  4. For each InheritanceMappingAttribute attribute, also add a Type property.

    This property holds a value that specifies which class or subclass the key value signifies.

  5. On only one of the InheritanceMappingAttribute attributes, add an IsDefault property.

    This property serves to designate a fallback mapping when the discriminator value from the database table does not match any Code value in the inheritance mappings.

  6. Add an IsDiscriminator property for a ColumnAttribute attribute.

    This property signifies that this is the column that holds the Code value.

Note Note

If you are using Visual Studio, you can use the Object Relational Designer to configure inheritance. How to: Configure Inheritance by Using the O/R Designer
How to: Configure Inheritance by Using the O/R Designer

In the following code example, Vehicle is defined as the root class, and the previous steps have been implemented to describe the hierarchy for LINQ. The following illustration shows the relationships.

[Table]
[InheritanceMapping(Code = "C", Type = typeof(Car))]
[InheritanceMapping(Code = "T", Type = typeof(Truck))]
[InheritanceMapping(Code = "V", Type = typeof(Vehicle),
    IsDefault = true)]
public class Vehicle
{
    [Column(IsDiscriminator = true)]
    public string DiscKey;
    [Column(IsPrimaryKey = true)]
    public string VIN;
    [Column]
    public string MfgPlant;
}
public class Car : Vehicle
{
    [Column]
    public int TrimCode;
    [Column]
    public string ModelName;
}

public class Truck : Vehicle
{
    [Column]
    public int Tonnage;
    [Column]
    public int Axles;
}
Show:
© 2014 Microsoft