更新:November 2007
若要在 LINQ 中执行继承映射,您必须按以下步骤中的说明在继承层次结构的根类中指定属性 (Attribute) 和属性 (Attribute) 的属性 (Property)。使用 Visual Studio 的开发人员还可以使用 对象关系设计器 来映射继承层次结构。
| .gif) 说明: | 
|---|
| 子类中不需要具有特殊属性 (Attribute) 或属性 (Property)。请特别注意,子类不具有 TableAttribute 属性。 | 
映射继承层次结构
- 向根类添加 TableAttribute 属性。 
- 为层次结构中的每个类添加 InheritanceMappingAttribute 属性,同样是添加到根类中。 
- 为每个 InheritanceMappingAttribute 属性 (Attribute),定义一个 Code 属性 (Property)。 - 此属性 (Property) 保存一个值,该值显示在数据库表的 IsDiscriminator 列中,用来指示该行数据所属的类或子类。 
- 为每个 InheritanceMappingAttribute 属性 (Attribute),也添加一个 Type 属性 (Property)。 - 此属性 (Property) 保存一个值,此值指定键值所表示的类或子类。 
- 仅在其中一个 InheritanceMappingAttribute 属性 (Attribute) 上,添加一个 IsDefault 属性 (Property)。 - 此属性 (Property) 用来在数据库表中的鉴别器值在继承映射中不与任何 Code 值匹配时指定回退映射。 
- 为 ColumnAttribute 属性 (Attribute) 添加一个 IsDiscriminator 属性 (Property)。 - 此属性 (Property) 表示这是保存 Code 值的列。 
示例
| .gif) 说明: | 
|---|
| 如果您使用的是 Visual Studio,则可以使用 对象关系设计器 来配置继承。 | 
在下面的代码示例中,Vehicle 定义为根类,并且已执行前面的步骤来说明 LINQ 的层次结构。下图显示了这些关系。
.png)
<Table()> _
<InheritanceMapping(Code:="C", Type:=GetType(Car))> _
<InheritanceMapping(Code:="T", Type:=GetType(Truck))> _
<InheritanceMapping(Code:="V", Type:=GetType(Vehicle), _
    IsDefault:=True)> _
Public Class Vehicle
    <Column(IsDiscriminator:=True)> _
        Private DiscKey As String
    <Column(IsPrimaryKey:=True)> _
        Private VIN As String
    <Column()> _
        Private MfgPlant As String
End Class
Public Class Car
    Inherits Vehicle
    <Column()> _
        Private TrimCode As Integer
    <Column()> _
        Private ModelName As String
End Class
Public Class Truck
    Inherits Vehicle
    <Column()> _
        Private Tonnage As Integer
    <Column()> _
        Private Axles As Integer
End Class
[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;
}