LINQ to SQL 物件模型

在 LINQ to SQL 中,以開發人員之程式設計語言表示的物件模型會對應至關聯式資料庫的資料模型。 然後就會根據物件模型對資料執行作業。

在這種情況下,您不會發出資料庫命令 (例如,INSERT) 至資料庫。 而是在您的物件模型中變更值和執行方法。 當您要查詢資料庫或將變更傳送至資料庫時,LINQ to SQL 會將您的要求轉譯為正確的 SQL 命令,並將這些命令傳送至資料庫。

Screenshot that shows the Linq Object Model.

下表摘要說明 LINQ to SQL 物件模型中最基本的項目,以及其與關聯式資料模型中項目的關聯性:

LINQ to SQL 物件模型 關聯式資料模型
實體類別 Table
類別成員 資料行
關聯 外部索引鍵關聯性
方法 預存程序或函式

注意

下列說明假設您對於關聯式資料模型和規則有基本知識。

LINQ to SQL 實體類別和資料庫資料表

在 LINQ to SQL 中,資料庫資料表是由實體類別所表示。 實體類別就像您可能建立的任何其他類別,但您會使用能讓類別與資料庫資料表產生關聯的特殊資訊來標註此類別。 您可將自訂屬性 (TableAttribute) 加入至您的類別宣告,藉以產生此附註,如下列範例所示:

範例

[Table(Name = "Customers")]
public class Customerzz
{
    public string CustomerID;
    // ...
    public string City;
}
<Table(Name:="Customers")> _
Public Class Customer
    Public CustomerID As String
    ' ...
    Public City As String
End Class

只有宣告為資料表的類別執行個體 (也就是實體類別) 可以儲存至資料庫。

如需詳細資訊,請參閱屬性架構對應的 <資料表屬性> 一節。

LINQ to SQL 類別成員和資料庫資料行

除了使類別和資料表產生關聯以外,您還會指定欄位或屬性,以表示資料庫資料行。 基於這個目的,LINQ to SQL 會定義 ColumnAttribute 屬性,如下列範例所示:

範例

[Table(Name = "Customers")]
public class Customer
{
    [Column(IsPrimaryKey = true)]
    public string CustomerID;
    [Column]
    public string City;
}
<Table(Name:="Customers")> _
Public Class Customer
    <Column(IsPrimaryKey:=True)> _
    Public CustomerID As String

    <Column()> _
    Public City As String
End Class

只有對應到資料行的欄位和屬性會保存至資料庫或自資料庫擷取。 至於未宣告為資料行者,則會被視為應用程式邏輯的暫時性部分。

ColumnAttribute 屬性 (Attribute) 具有各種屬性 (Property),您可以用於自訂表示資料行的這些成員 (例如,指定成員以表示主索引鍵資料行)。 如需詳細資訊,請參閱屬性架構對應的 <資料行屬性> 一節。

LINQ to SQL 關聯和資料庫外部索引鍵關聯性

在 LINQ to SQL 中,您可藉由套用 AssociationAttribute 屬性來表示資料庫關聯 (例如,外部索引鍵和主索引鍵的關聯性)。 在下列程式碼區段中,Order 類別包含具有 AssociationAttribute 屬性 (Attribute) 的 Customer 屬性 (Property)。 這個屬性 (Property) 與其屬性 (Attribute) 提供了與 Order 類別有關的 Customer 類別。

下列程式碼範例顯示 Customer 類別中的 Order 屬性 (Property)。

範例

[Association(Name="FK_Orders_Customers", Storage="_Customer", ThisKey="CustomerID", IsForeignKey=true)]
public Customer Customer
{
    get
    {
        return this._Customer.Entity;
    }
    set
    {
        Customer previousValue = this._Customer.Entity;
        if (((previousValue != value)
                    || (this._Customer.HasLoadedOrAssignedValue == false)))
        {
            this.SendPropertyChanging();
            if ((previousValue != null))
            {
                this._Customer.Entity = null;
                previousValue.Orders.Remove(this);
            }
            this._Customer.Entity = value;
            if ((value != null))
            {
                value.Orders.Add(this);
                this._CustomerID = value.CustomerID;
            }
            else
            {
                this._CustomerID = default(string);
            }
            this.SendPropertyChanged("Customer");
        }
    }
}
<Association(Name:="FK_Orders_Customers", Storage:="_Customer", ThisKey:="CustomerID", IsForeignKey:=true)>  _
Public Property Customer() As Customer
    Get
        Return Me._Customer.Entity
    End Get
    Set
        Dim previousValue As Customer = Me._Customer.Entity
        If (((previousValue Is value)  _
                    = false)  _
                    OrElse (Me._Customer.HasLoadedOrAssignedValue = false)) Then
            Me.SendPropertyChanging
            If ((previousValue Is Nothing)  _
                        = false) Then
                Me._Customer.Entity = Nothing
                previousValue.Orders.Remove(Me)
            End If
            Me._Customer.Entity = value
            If ((value Is Nothing)  _
                        = false) Then
                value.Orders.Add(Me)
                Me._CustomerID = value.CustomerID
            Else
                Me._CustomerID = CType(Nothing, String)
            End If
            Me.SendPropertyChanged("Customer")
        End If
    End Set
End Property

如需詳細資訊,請參閱屬性架構對應的 <關聯屬性> 一節。

LINQ to SQL 方法和資料庫預存程序

LINQ to SQL 支援預存程序和使用者定義函式。 在 LINQ to SQL 中,您可將這些資料庫定義的抽象對應至用戶端物件,便可以強型別的方式從用戶端程式碼存取這些抽象。 方法簽章與資料庫中定義的程序和函式簽章十分相似。 您可以使用 IntelliSense 來探索這些方法。

呼叫對應程序所傳回的結果集是強型別集合。

LINQ to SQL 會使用 FunctionAttributeParameterAttribute 屬性,將預存程序和函式對應至方法。 IsComposable 屬性可以區分表示預存程序的方法和表示使用者定義函式的方法。 如果此屬性設為 false (預設值),則此方法表示預存程序。 如果設為 true,則此方法表示資料庫函式。

注意

如果您使用的是 Visual Studio,則可以使用「物件關聯式設計工具」來建立對應到預存程序和使用者定義函式的方法。

範例

// This is an example of a stored procedure in the Northwind
// sample database. The IsComposable property defaults to false.
[Function(Name="dbo.CustOrderHist")]
public ISingleResult<CustOrderHistResult> CustOrderHist([Parameter(Name="CustomerID", DbType="NChar(5)")] string customerID)
{
    IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), customerID);
    return ((ISingleResult<CustOrderHistResult>)(result.ReturnValue));
}
   ' This is an example of a stored procedure in the Northwind
   ' sample database. The IsComposable property defaults to false.
   <FunctionAttribute(Name:="dbo.CustOrderHist")> _
Public Function CustOrderHist(<Parameter(Name:="CustomerID", DbType:="NChar(5)")> ByVal customerID As String) As ISingleResult(Of CustOrderHistResult)
       Dim result As IExecuteResult = Me.ExecuteMethodCall(Me, CType(MethodInfo.GetCurrentMethod, MethodInfo), customerID)
       Return CType(result.ReturnValue, ISingleResult(Of CustOrderHistResult))
   End Function

如需詳細資訊,請參閱屬性架構對應預存程序的 <函式屬性>、<預存程序屬性> 及 <參數屬性> 各節。

另請參閱