Passo a passo: consultar entre relações (Visual Basic)Walkthrough: Querying Across Relationships (Visual Basic)
Este tutorial demonstra o uso de LINQ to SQLLINQ to SQL associações para representar relações de chave estrangeira no banco de dados.This walkthrough demonstrates the use of LINQ to SQLLINQ to SQL associations to represent foreign-key relationships in the database.
Observação
Seu computador pode mostrar diferentes nomes ou locais para alguns dos elementos de interface do usuário do Visual Studio nas instruções a seguir.Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. A edição do Visual Studio que você possui e as configurações que você usa determinam esses elementos.The Visual Studio edition that you have and the settings that you use determine these elements. Para obter mais informações, consulte Personalizando o IDE.For more information, see Personalizing the IDE.
Este passo a passo foi escrito usando as Configurações de Desenvolvimento do Visual Basic.This walkthrough was written by using Visual Basic Development Settings.
Pré-requisitosPrerequisites
Você deve ter concluído a explicação: modelo de objeto simples e consulta (Visual Basic).You must have completed Walkthrough: Simple Object Model and Query (Visual Basic). Este passo a passo é baseado naquele, incluindo a presença do arquivo northwnd.mdf em c:\linqtest.This walkthrough builds on that one, including the presence of the northwnd.mdf file in c:\linqtest.
Visão geralOverview
Este passo a passo consiste em três tarefas principais:This walkthrough consists of three main tasks:
Adicionando uma classe de entidade para representar a tabela Orders no banco de dados de exemplo Northwind.Adding an entity class to represent the Orders table in the sample Northwind database.
Suplementando anotações à classe
Customer
para aprimorar a relação entre as classesCustomer
eOrder
.Supplementing annotations to theCustomer
class to enhance the relationship between theCustomer
andOrder
classes.Criando e executando uma consulta para testar o processo de obtenção de informações de
Order
usando a classeCustomer
.Creating and running a query to test the process of obtainingOrder
information by using theCustomer
class.
Relações de mapeamento entre tabelasMapping Relationships across Tables
Depois de definir a classe Customer
, crie a definição da classe de entidade Order
que inclui o código a seguir, que indica que Orders.Customer
se relaciona como uma chave estrangeira a Customers.CustomerID
.After the Customer
class definition, create the Order
entity class definition that includes the following code, which indicates that Orders.Customer
relates as a foreign key to Customers.CustomerID
.
Para adicionar a classe de entidade OrderTo add the Order entity class
Digite ou cole o código a seguir depois da classe
Customer
:Type or paste the following code after theCustomer
class:<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
Anotando a classe CustomerAnnotating the Customer Class
Nesta etapa, você anota a classe Customer
para indicar sua relação com a classe Order
.In this step, you annotate the Customer
class to indicate its relationship to the Order
class. Essa adição não é estritamente necessária, porque a definição da relação em qualquer direção é suficiente para criar o link.(This addition is not strictly necessary, because defining the relationship in either direction is sufficient to create the link. Mas a adição dessa anotação permite que você navegue objetos facilmente em qualquer direção.But adding this annotation does enable you to easily navigate objects in either direction.)
Para anotar a classe CustomerTo annotate the Customer class
Digite ou cole o código a seguir na classe
Customer
:Type or paste the following code into theCustomer
class: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
Criando e executando uma consulta pela relação de Customer-OrderCreating and Running a Query across the Customer-Order Relationship
Agora você pode acessar objetos Order
diretamente nos objetos Customer
ou na ordem oposta.You can now access Order
objects directly from the Customer
objects, or in the opposite order. Você não precisa de uma junção explícita entre clientes e pedidos.You do not need an explicit join between customers and orders.
Para acessar objetos Order usando objetos CustomerTo access Order objects by using Customer objects
Modifique o método
Sub Main
digitando ou colando o seguinte código no método:Modify theSub Main
method by typing or pasting the following code into the method:' 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)
Pressione F5 para depurar seu aplicativo.Press F5 to debug your application.
Dois nomes aparecem na caixa de mensagem, e a janela Console mostra o código SQL gerado.Two names appear in the message box, and the Console window shows the generated SQL code.
Feche a caixa de mensagem para interromper a depuração.Close the message box to stop debugging.
Criando uma exibição fortemente tipada do seu banco de dadosCreating a Strongly Typed View of Your Database
É muito mais fácil começar com uma exibição fortemente tipada do seu banco de dados.It is much easier to start with a strongly typed view of your database. Com o objeto DataContext fortemente tipado, você não precisa de chamadas para GetTable.By strongly typing the DataContext object, you do not need calls to GetTable. Você pode usar tabelas fortemente tipadas em todas as consultas quando usa o objeto DataContext fortemente tipado.You can use strongly typed tables in all your queries when you use the strongly typed DataContext object.
Nas etapas a seguir, você criará Customers
como uma tabela fortemente tipada que mapeia para a tabela Customers no banco de dados.In the following steps, you will create Customers
as a strongly typed table that maps to the Customers table in the database.
Para tornar o objeto DataContext fortemente tipadoTo strongly type the DataContext object
Adicione o código a seguir acima da declaração da classe
Customer
.Add the following code above theCustomer
class declaration.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
Modifique
Sub Main
para usar o DataContext fortemente tipado da seguinte maneira:ModifySub Main
to use the strongly typed DataContext as follows:' 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()
Pressione F5 para depurar seu aplicativo.Press F5 to debug your application.
A saída da janela Console é:The Console window output is:
ID=WHITC
Pressione Enter na janela Console para fechar o aplicativo.Press Enter in the Console window to close the application.
No menu arquivo , clique em salvar tudo se desejar salvar este aplicativo.On the File menu, click Save All if you want to save this application.
Próximas etapasNext Steps
A próxima instrução (Walkthrough: Manipulando dados (Visual Basic)) demonstra como manipular dados.The next walkthrough (Walkthrough: Manipulating Data (Visual Basic)) demonstrates how to manipulate data. Esse passo a passo não requer que você salve os dois tutoriais passo a passo desta série que você já concluiu.That walkthrough does not require that you save the two walkthroughs in this series that you have already completed.