Compartilhar via


Como: retornar um resultado da consulta LINQ como um tipo específico (Visual Basic)

Language-Integrated Query (LINQ) makes it easy to access database information and execute queries. By default, LINQ queries return a list of objects as an anonymous type. You can also specify that a query return a list of a specific type by using the Select clause.

The following example shows how to create a new application that performs queries against a SQL Server database and projects the results as a specific named type. For more information, see Tipos anônimos (Visual Basic) and Cláusula Select (Visual Basic).

The examples in this topic use the Northwind sample database. If you do not have the Northwind sample database on your development computer, you can download it from the Microsoft Download Center Web site. For instructions, see Downloading Sample Databases (LINQ to SQL).

ObservaçãoObservação

Seu computador pode mostrar nomes ou locais diferentes para alguns dos elementos da interface do usuário do Visual Studio nas instruções a seguir. A edição do Visual Studio que você possui e as configurações que você usa determinam esses elementos. Para obter mais informações, consulte Configurações do Visual Studio.

To create a connection to a database

  1. In Visual Studio, open Server Explorer/Database Explorer by clicking Server Explorer/Database Explorer on the View menu.

  2. Right-click Data Connections in Server Explorer/Database Explorer and then click Add Connection.

  3. Specify a valid connection to the Northwind sample database.

To add a project that contains a LINQ to SQL file

  1. In Visual Studio, on the File menu, point to New and then click Project. Select Visual Basic Windows Forms Application as the project type.

  2. On the Project menu, click Add New Item. Select the LINQ to SQL Classes item template.

  3. Name the file northwind.dbml. Click Add. O Object Relational Designer (Designer Relacional de Objetos) é aberto para o northwind.dbml arquivo.

To add tables to query to the O/R Designer

  1. In Server Explorer/Database Explorer, expand the connection to the Northwind database. Expand the Tables folder.

    Se você tiver fechado o Designer Relacional de Objetos, poderá reabri-lo por duas-clicando na northwind.dbml o arquivo que você adicionou anteriormente.

  2. Click the Customers table and drag it to the left pane of the designer.

    The designer creates a new Customer object for your project. You can project a query result as the Customer type or as a type that you create. This sample will create a new type in a later procedure and project a query result as that type.

  3. Save your changes and close the designer.

  4. Save your project.

To add code to query the database and display the results

  1. From the Toolbox, drag a DataGridView control onto the default Windows Form for your project, Form1.

  2. Double-click Form1 to modify the Form1 class.

  3. After the End Class statement of the Form1 class, add the following code to create a CustomerInfo type to hold the query results for this sample.

    Public Class CustomerInfo
      Public Property CompanyName As String
      Public Property ContactName As String
    End Class
    
  4. When you added tables to the O/R Designer, the designer added a DataContext object to your project. This object contains the code that you must have to access those tables, and to access individual objects and collections for each table. The DataContext object for your project is named based on the name of your .dbml file. For this project, the DataContext object is named northwindDataContext.

    You can create an instance of the DataContext in your code and query the tables specified by the O/R Designer.

    In the Load event of the Form1 class, add the following code to query the tables that are exposed as properties of your data context. The Select clause of the query will create a new CustomerInfo type instead of an anonymous type for each item of the query result.

    Dim db As New northwindDataContext
    
    Dim customerList =
      From cust In db.Customers
      Where cust.CompanyName.StartsWith("L")
      Select New CustomerInfo With {.CompanyName = cust.CompanyName,
                                    .ContactName = cust.ContactName}
    
    DataGridView1.DataSource = customerList
    
  5. Press F5 to run your project and view the results.

Consulte também

Tarefas

Walkthrough: Creating LINQ to SQL Classes (O/R Designer)

Conceitos

DataContext Methods (O/R Designer)

Outros recursos

LINQ no Visual Basic

Consultas(Visual Basic)

LINQ to SQL