共用方式為


HOW TO:對應繼承階層架構 (LINQ to SQL)

更新: November 2007

若要在 LINQ 中實作繼承對應,您必須如下列步驟所述,在繼承階層架構 (Inheritance Hierarchy) 的根類別上指定屬性 (Attribute) 與其屬性 (Property)。使用 Visual Studio 的開發人員可以使用物件關聯式設計工具來對應繼承階層架構。

注意事項:

子類別上不需要任何特別的屬性 (Attribute) 或屬性 (Property)。請特別注意,子類別沒有 TableAttribute 屬性 (Attribute)。

若要對應繼承階層架構

  1. TableAttribute 屬性 (Attribute) 加入至根類別。

  2. 同樣在根類別中,加入階層結構中每個類別的 InheritanceMappingAttribute 屬性 (Attribute)。

  3. 針對每個 InheritanceMappingAttribute 屬性 (Attribute),定義 Code 屬性 (Property)。

    這個屬性 (Property) 保留的值會顯示在資料庫資料表的 IsDiscriminator 資料行中,以表示此資料列屬於哪個類別或子類別。

  4. 針對每個 InheritanceMappingAttribute 屬性 (Attribute),同時加入 Type 屬性 (Property)。

    這個屬性 (Property) 保留的值會指定索引鍵值所表示的類別或子類別。

  5. 僅在其中一個 InheritanceMappingAttribute 屬性 (Attribute) 中,加入 IsDefault 屬性 (Property)。

    當資料庫資料表中的鑑別子值不符合繼承對應中的任何 Code 值時,這個屬性 (Property) 即可用於指定「後援」(Fallback) 對應。

  6. 加入 ColumnAttribute 屬性 (Attribute) 的 IsDiscriminator 屬性 (Property)。

    這個屬性 (Property) 表示此為保留 Code 值的資料行。

範例

注意事項:

如果您使用的是 Visual Studio,就可以使用物件關聯式設計工具來設定繼承。

在下列程式碼範例中,Vehicle 會定義為根類別,而且會實作先前的步驟以描述 LINQ 的階層架構。下圖顯示關聯性。

繼承圖表

<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;
}

請參閱

概念

繼承支援 (LINQ to SQL)

其他資源

HOW TO:使用程式碼編輯器自訂實體類別 (LINQ to SQL)