"));
Visual Studio 2008 Training Kit Descobrir CSS’s que não estão a ser usados… Visual Studio 2008 Training Kit Discover CSS that's not being used ...
Nov 27 Nov 27

image

O LINQ é constituído por vários “providers” (fornecedores), ao estilo do que já estávamos habituados para o Membership ou para o Profile. The LINQ is composed of several "providers" (suppliers), the style of what we've been accustomed to the Membership or the Profile. Os providers que vêm de origem permitem efectuar consultas sobre xml, objectos e obviamente SQL. The providers who come from home to carry out consultations on xml, and of course SQL objects.


Neste post vou demonstrar um exemplo do uso do LINQ para consultar a famosa base de dados Northwind. In this post I will demonstrate an example of the use of LINQ to view the famous Northwind database.

Vamos começar por criar uma nova web application no Visual Studio 2008 denominada “LINQDemo”. Let's start by creating a new Web application in Visual Studio called 2008 "LINQDemo".
Nesta aplicação vamos adicionar um novo item do tipo “LINQ to SQL Classes”, que vamos denominar de “Northwind.dbml”. In this application we will add a new item like "LINQ to SQL Classes", which we termed "Northwind.dbml."

image

Este ficheiro vai “gerar” uma representação em objectos de elementos da base de dados, que é vulgarmente conhecido como ORM (Object Relational Mapping). This file will "generate" a representation of elements of objects in the database, which is commonly known as ORM (Object Relational Mapping).
Depois de criado, temos uma interface em branco, onde nos é sugerido, para criarmos classes, arrastando objectos da Toolbox ou do ServerExplorer. After you set up, we have an interface in white, which we suggested, to create classes, dragging objects from the Toolbox or ServerExplorer. Estas classes serão a representação dos dados na base de dados. These classes will be the representation of data in the database.

image

Vamos então arrastar a tabela Products ea tabela Categories da base de dados Northwind, a partir do Server Explorer, que como podem ver na imagem anterior, já está aberto do lado direito. We will then drag the table Products and Categories table of Northwind database from the Server Explorer, which as you can see in the picture above, is already open on the right.

(Se necessitarem de informação de como configurar a base de dados Northwind, enviem-me um email para blog.istomesmo@gmail.com ou deixem um comentário) (If you need information on how to configure the database Northwind, send me an email to blog.istomesmo @ gmail.com or leave a comment)

image

Como podemos ver na imagem anterior, todas as definições das tabelas são reconhecidas, incluindo as suas chaves, e até as relações entre tabelas. As we can see in the picture above, all settings of the tables are recognized, including her keys, and even the relationships between tables. Agora basta-nos guardar o ficheiro acabado de criar. Now just save us the file you just created.

Neste momento já temos estas duas tabelas da base de dados com uma representação por objectos. We already have these two tables of the database with a representation of objects.
Vamos agora dar início à consulta de dados nestas tabelas. We will now begin the consultation of data in these tables. Para isso vamos adicionar uma GridView à Default.aspx. To this we add a GridView to the Default.aspx. Nesta GridView podemos escolher um dos estilos predefinidos. This GridView can choose one of predefined styles.

image

Já temos o interface para apresentar os nossos dados, por isso, vamos passar para o code behind da página. We already have the interface to display our data, so we will move to the code behind the page. No Page_Load, vamos dizer que queremos listar todos os produtos da base de dados. In Page_Load, we say we want to list all products from the database. Primeiro vamos definir o contexto, ou seja , indicar em que base de dados é que queremos efectuar a consulta. First let's set the context, or indicate where the database is that we want to make the appointment. Este NorthWindDataContext foi gerado quando criámos o ficheiro Northwind.dbml. This NorthWindDataContext was generated when we created the file Northwind.dbml.
Depois de termos o contexto, vamos efectuar a query (consulta). After we have the context, we will make the query (query). Uma query é sempre uma variável não tipada, pois não sabemos quais os dados que serão devolvidos pela mesma. A query is always a variable tipada not because we do not know what data will be returned by the same.

A sintaxe do LINQ tem algumas semelhanças com o SQL, mas funciona de modo inverso, ou seja, primeiro temos o “from” e só depois o “select”. The syntax of LINQ has some similarities to SQL, but works in reverse order, that is, first we have the "from" and then the "select". Uma das razões para que o LINQ funcione desta forma é o intellisense, pois só desta forma podemos ter intellisense em toda a query, pois já sabemos qual o sítio(tabela) em que vamos efectuar a consulta, e assim, intellisense consegue dar as hipóteses correctas. One reason for the LINQ work this way is the IntelliSense, because only this way can we have IntelliSense throughout the query, because we know what the site (table) in which we conduct the consultation, and thus can give the chances IntelliSense correct.

Na consulta que desejamos efectuar, queremos todos os produtos (p) da tabela Produtos (Products) do contexto indicado (database). We wish to make in the consultation, we want all the products (p) of the table Products (Products) of the indicated (database).

image

No final da query, basta fazermos o databind dos dados para a gridview, e teremos todas as propriedades da tabela produtos a serem apresentadas na gridview. At the end of the query, just do the databind data to gridview, and we all properties of the scale products to be displayed in gridview.

image

Por tras de tudo isto, o LINQ está a gerar SQL para aceder à base de dados e obter os dados que nós definimos na query. Behind all this, LINQ is generating SQL to access the database and obtain the data that we define the query. Para vermos o SQL gerado, podemos adicionar mais um comando ao Page_Load. To see the generated SQL, we can add a command to Page_Load.

image

Se corrermos a página novamente, antes da GridView, vamos ver o SQL utilizado pelo LINQ para obter os valores apresentados. If we run the page again, before the GridView, we see the SQL used by LINQ to obtain the figures.

image

Neste caso trata-se de um SELECT simples. In this case it is a simple SELECT.

Vamos agora alterar o nosso código para devolver apenas o produtos que façam parte de uma categoria que contenha no seu nome “con”. We will now change our code to return only the products that are part of a category that contains your name in the "con".

image

Como podem ver pelo código necessário, facilmente conseguimos efectuar um join de tabelas, de uma forma simples. As you can see the code necessary, easily able to make a join table in a simple manner.

image

Apenas os produtos que fazem parte das categorias 2 e 3 são devolvidos. Only products that are part of category 2 and 3 are returned. Reparem no SQL gerado pelo LINQ. Look at SQL generated by LINQ.

Se apenas quiséssemos obter o nome do produto ea respectiva categoria, bastava-nos alterar a query para: If only we wanted to get the name of the product and its category, suffice us to change the query:

image

Assim na GridView obteríamos: So get in GridView:

image

Como podemos ver, o LINQ permite-nos aceder rapidamente aos dados, de uma forma simples, com intellisense, e através de uma query tipada, em que os possíveis erros de sintaxe são validados na altura da compilação, fazendo com que consigamos descobrir os erros mesmo antes de testar o código. As we can see, the LINQ allows us to quickly access the data in a simple manner, with IntelliSense and through a query tipada, where the possible errors of syntax are validated at the time of compilation, so we can find the errors even before testing the code.

Em posts futuros, voltarei a falar sobre este novo modelo de programação, o LINQ. In future posts, I will talk about this new programming model, the LINQ.

Deixem as vossas opiniões sobre o LINQ, gostaria muito de saber o que acham, se já usam, se estão a pensar usar, etc… Let your views on LINQ, I would like to know what to think, if already use, are used to thinking, etc ...


publicado por NC Etiquetas: 101 , 13 , 54 , 69 , 78 , 86 , 92 published by NC Etiquetas: 101, 13, 54, 69, 78, 86, 92

3 Responses a “LINQ (Language Integrated Query)” 3 Responses to "LINQ (Language Integrated Query)"

  1. Novidades do Visual Studio 2008 « Isto Mesmo Diz: What's New in Visual Studio 2008 "Even That Says:

    [...] » LINQ (Language Integrated Query) [...] [...] "LINQ (Language Integrated Query) [...]

  2. rascunho » Blog Archive » links for 2007-12-21 Diz: Draft »Blog Archive» links for 2007-12-21 Says:

    [...] LINQ (Language Integrated Query) « Isto Mesmo O LINQ é constituído por vários “providers” (fornecedores), ao estilo do que já estávamos habituados para o Membership ou para o Profile. [...] LINQ (Language Integrated Query) 'Even The LINQ This consists of several "providers" (suppliers), the style of what we've been accustomed to the Membership or the Profile. Os providers que vêm de origem permitem efectuar consultas sobre xml, objectos e obviamente SQL. The providers who come from home to carry out consultations on xml, and of course SQL objects. (tags: istomesmo.wordpress.com 2007 mes11 dia21 at_tecp Linq ASP.NET C# blog_post) [...] (tags: istomesmo.wordpress.com 2007 mes11 day21 at_tecp Linq ASP.NET C # blog_post) [...]

  3. Rui Lima Diz: Rui Lima Says:

    muito bom! very good!

Deixar uma resposta Leave a Reply