共用方式為


逐步解說:跨關聯性查詢 (Visual Basic)

此逐步解說示範如何使用 LINQ to SQL 關聯 (Association) 來表示資料庫中的外部索引鍵關聯性 (Relationship)。

注意

在下列指示的某些 Visual Studio 使用者介面項目中,您的電腦可能會顯示不同的名稱或位置: 您所擁有的 Visual Studio 版本以及使用的設定會決定這些項目。 如需詳細資訊,請參閱將 Visual Studio IDE 個人化

這個逐步解說是使用 Visual Basic 開發設定所撰寫。

必要條件

您必須已完成逐步解說:簡單物件模型和查詢 (Visual Basic)。 本逐步解決建置於該逐步解決之上,包含存在於 c:\linqtest 中的 northwnd.mdf 檔。

概觀

此逐步解說包含三項主要工作:

  • 加入實體類別,以表示 Northwind 範例資料庫中的 Orders 資料表。

  • 補充 Customer 類別的附註,以加強 CustomerOrder 類別之間的關聯性。

  • 建立和執行查詢,以測試使用 Order 類別取得 Customer 資訊的處理序。

跨資料表對應關聯性

Customer 類別定義之後,建立包含下列程式碼的 Order 實體類別定義,這表示 Orders.CustomerCustomers.CustomerID 的外部索引鍵。

若要加入 Order 實體類別

  • Customer 類別之後輸入或貼上下列程式碼:

    <Table(Name:="Orders")> _
    Public Class Order
        Private _OrderID As Integer
        Private _CustomerID As String
        Private _Customers As EntityRef(Of Customer)
    
        Public Sub New()
            Me._Customers = New EntityRef(Of Customer)()
        End Sub
    
        <Column(Storage:="_OrderID", DbType:="Int NOT NULL IDENTITY", _
            IsPrimaryKey:=True, IsDBGenerated:=True)> _
        Public ReadOnly Property OrderID() As Integer
            Get
                Return Me._OrderID
            End Get
        End Property
        ' No need to specify a setter because IsDBGenerated is true.
    
        <Column(Storage:="_CustomerID", DbType:="NChar(5)")> _
        Public Property CustomerID() As String
            Get
                Return Me._CustomerID
            End Get
            Set(ByVal value As String)
                Me._CustomerID = value
            End Set
        End Property
    
        <Association(Storage:="_Customers", ThisKey:="CustomerID")> _
        Public Property Customers() As Customer
            Get
                Return Me._Customers.Entity
            End Get
            Set(ByVal value As Customer)
                Me._Customers.Entity = value
            End Set
        End Property
    End Class
    

加入 Customer 類別的附註

在這個步驟中,您會加入 Customer 類別的附註,指出其與 Order 類別的關聯性 (此加入動作並非絕對必要,因為定義任一方向的關聯性就足以建立連結。但加入此附註確實可讓您輕易地以任一方向巡覽物件)。

若要標註 Customer 類別

  • 將下列程式碼輸入或貼到 Customer 類別中:

    Private _Orders As EntitySet(Of Order)
    
    Public Sub New()
        Me._Orders = New EntitySet(Of Order)()
    End Sub
    
    <Association(Storage:="_Orders", OtherKey:="CustomerID")> _
    Public Property Orders() As EntitySet(Of Order)
        Get
            Return Me._Orders
        End Get
        Set(ByVal value As EntitySet(Of Order))
            Me._Orders.Assign(value)
        End Set
    End Property
    

建立和執行客戶-訂單關聯性的查詢

您現在可以直接從 Order 物件存取 Customer 物件,反之亦然。 您不需要客戶和訂單之間的明確聯結 (Join)。

若要使用 Customer 物件存取 Order 物件

  1. 將下列程式碼輸入或貼到 Sub Main 方法,進而修改此方法:

    ' Query for customers who have no orders.
    Dim custQuery = _
        From cust In Customers _
        Where Not cust.Orders.Any() _
        Select cust
    
    Dim msg As String = "", title As String = _
        "Customers With No Orders", response As MsgBoxResult, _
        style As MsgBoxStyle = MsgBoxStyle.Information
    
    For Each custObj In custQuery
        msg &= String.Format(custObj.CustomerID & vbCrLf)
    Next
    response = MsgBox(msg, style, title)
    
  2. 按 F5 對應用程式進行偵錯。

    訊息方塊中會出現兩個名稱,而主控台視窗則會顯示所產生的 SQL 程式碼。

  3. 關閉訊息方塊以停止偵錯。

建立資料庫的強型別檢視

從資料庫的強型別檢視著手會容易許多。 透過建立強型別 DataContext 物件,您就不需要呼叫 GetTable。 當您使用強型別 DataContext 物件時,可以在所有查詢中使用強型別資料表。

在下列步驟中,您會將 Customers 建立為強型別資料表,以對應資料庫中的 Customers 資料表。

若要建立強型別 DataContext 物件

  1. Customer 類別宣告之上加入下列程式碼。

    Public Class Northwind
        Inherits DataContext
        ' Table(Of T) abstracts database details  per
        ' table/data type.
        Public Customers As Table(Of Customer)
        Public Orders As Table(Of Order)
    
        Public Sub New(ByVal connection As String)
            MyBase.New(connection)
        End Sub
    End Class
    
  2. 修改 Sub Main 以使用強型別 DataContext,如下所示:

    ' Use a connection string.
    Dim db As New Northwind _
        ("C:\linqtest\northwnd.mdf")
    
    ' Query for customers from Seattle.
    Dim custs = _
        From cust In db.Customers _
        Where cust.City = "Seattle" _
        Select cust
    
    For Each custObj In custs
        Console.WriteLine("ID=" & custObj.CustomerID)
    Next
    
    ' Freeze the console window.
    Console.ReadLine()
    
  3. 按 F5 對應用程式進行偵錯。

    主控台視窗輸出為:

    ID=WHITC

  4. 在 [主控台] 視窗中按 Enter 鍵,以關閉應用程式。

  5. 如要儲存此應用程式,請按一下 [檔案] 功能表上的 [全部儲存]

後續步驟

下一個逐步解說 (逐步解說:操作資料 (Visual Basic)) 會示範如何操作資料。 該逐步解說並不要求您儲存這系列中已完成的兩個逐步解說。

另請參閱