29
Language Integrated Language Integrated Query Query Johnny Halife Johnny Halife Microsoft Student Microsoft Student Ambassador Ambassador Southworks Southworks

Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

Embed Size (px)

Citation preview

Page 1: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

Language Integrated Language Integrated Query Query

Johnny HalifeJohnny HalifeMicrosoft Student AmbassadorMicrosoft Student AmbassadorSouthworksSouthworks

Page 2: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

Un problema prácticoUn problema práctico

SistemaSistema

5 Stored 5 Stored ProceduresProcedures

ObjetoObjeto

DataAccessDataAccessRecursosRecursos

Page 3: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

AgendaAgenda

Qué es LINQ?Qué es LINQ?

Standard Query OperationsStandard Query Operations

DLINQDLINQ

ConclusionesConclusiones

Page 4: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

Qué es LINQ?Qué es LINQ?La programación hoy en díaLa programación hoy en día

Desarrollo Orientado a ObjetosDesarrollo Orientado a Objetos

Datos en tecnologías no OO.Datos en tecnologías no OO.

Distintos entornos de DesarrolloDistintos entornos de DesarrolloNo Intellisense, late bound, verboseNo Intellisense, late bound, verbose

T-SQL vs. .NET FrameworkT-SQL vs. .NET Framework

““Impedance Mismatch”Impedance Mismatch”

TransactionsTransactions

Nulls - 3-value logicNulls - 3-value logic

Normalized DataNormalized Data

Declarative QueriesDeclarative Queries

TransparencyTransparency

Exception HandlingException Handling

““Different” nullsDifferent” nulls

ObjectsObjects

Imperative operationsImperative operations

EncapsulationEncapsulation

Database WorldDatabase World Programming WorldProgramming World

Page 5: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

StandardStandardQueryQuery

OperatorsOperators

ObjectsObjects

DLinqDLinq(ADO.NET)(ADO.NET)

XLinqXLinq(System.Xml)(System.Xml)

<book> <title/> <author/> <year/> <price/></book>

XMLXML

.NET Language Integrated Query.NET Language Integrated Query

C#C# VBVB Others…Others…

SQLSQL WinFWinFSS

The LINQ ProjectThe LINQ Project

Page 6: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

ArquitecturaArquitectura

LINQ Query Objects SubmitChanges()

SQL Query Rows SQL or Stored Procs

DLinq(ADO.NET)

SQLServer

from c in db.Customersfrom c in db.Customerswhere c.City == "London"where c.City == "London"selectselect new { c.Name, c.Phone } new { c.Name, c.Phone }

select Name, Phoneselect Name, Phonefrom customersfrom customerswhere city = 'London'where city = 'London'

Application

Services:Services:- Change tracking- Change tracking- Concurrency control- Concurrency control- Object identity- Object identity

Page 7: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

Una consulta hoy en díaUna consulta hoy en día

SqlConnection c = new SqlConnection(…); c.Open(); SqlCommand cmd = new SqlCommand( @"SELECT c.Name, c.Phone

FROM Customers c WHERE c.City = @p0"

); cmd.Parameters.AddWithValue("@po", "London"); DataReader dr = c.Execute(cmd); while (dr.Read()) { string name = dr.GetString(0); string phone = dr.GetString(1); DateTime date = dr.GetDateTime(2); } dr.Close();

Queries entre comillas

Resultados no tipados

No hay checkeos en compilación

Argumentos literales

Page 8: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

Una consulta con LINQUna consulta con LINQ

public class Customerpublic class Customer{{ public int Id;public int Id; public string Name;public string Name; public string Phone;public string Phone; … …}}

Table<Customer> customers = db.Customers;Table<Customer> customers = db.Customers;

var contacts =var contacts = from c in customersfrom c in customers where c.City == "London"where c.City == "London" select new { c.Name, c.Phone };select new { c.Name, c.Phone };

Clases que describen

tablas

Las tablas son

colecciones

El query es nativo del lenguaje

Validación en tiempo de

compilación

Page 9: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

Demostracion #1Demostracion #1

Una consulta con LINQUna consulta con LINQ

Page 10: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

En qué esta basado LINQ?En qué esta basado LINQ?

En las innovaciones introducidas por C# 2.0 y En las innovaciones introducidas por C# 2.0 y C# 3.0C# 3.0

Page 11: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

Objetivos de C# 3.0Objetivos de C# 3.0

Integración de OOP, Relacional y Xml.Integración de OOP, Relacional y Xml.

Basarse en los fundamentos de C# 2.0.Basarse en los fundamentos de C# 2.0.

No atar los lenguajes a APIS especificos.No atar los lenguajes a APIS especificos.

Compatibilidad hacia atrás.Compatibilidad hacia atrás.

Page 12: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

Métodos de ExtensiónMétodos de ExtensiónAgregar metodos a clases (incluso selladas)Agregar metodos a clases (incluso selladas)Notación de cascada de puntos (tipica en OOP)Notación de cascada de puntos (tipica en OOP)Fácil de escribirFácil de escribir

Expresiones LambdaExpresiones LambdaNotación más clara y funcionalNotación más clara y funcionalSe pueden omitir los tipos de datos, se infieren.Se pueden omitir los tipos de datos, se infieren.Puede ser una expresión o una secuencia de sentenciasPuede ser una expresión o una secuencia de sentencias

Inicialización de ObjetosInicialización de ObjetosYa no es necesario declarar tantas sobrecargas del c’tor como Ya no es necesario declarar tantas sobrecargas del c’tor como inicializaciones posibles hay del objeto.inicializaciones posibles hay del objeto.Inicialización de CollectionsInicialización de Collections

Tipos AnónimosTipos AnónimosSirven para el resultado de las querysSirven para el resultado de las querys

Inferencia de TiposInferencia de TiposCodificación más claraCodificación más claraPosibilidad de trabajar con tipos anónimosPosibilidad de trabajar con tipos anónimos

En qué esta basado LINQ?En qué esta basado LINQ?Innovaciones C# 3.0Innovaciones C# 3.0

Page 13: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

Demostracion #2Demostracion #2

C# 3.0 FeaturesC# 3.0 Features

Page 14: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

AgendaAgenda

Qué es LINQ?Qué es LINQ?

Standard Query OperationsStandard Query Operations

DLINQDLINQ

ConclusionesConclusiones

Page 15: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

Standard Query OperationsStandard Query OperationsAccediendo Objetos con LINQAccediendo Objetos con LINQ

Expresiones de Consulta con LINQExpresiones de Consulta con LINQ

fromfrom idid inin sourcesource

{ { fromfrom idid inin sourcesource | | wherewhere conditioncondition } }

[ [ orderbyorderby orderingordering, , orderingordering, … ], … ]

selectselect exprexpr | | groupgroup exprexpr byby keykey

[ [ intointo idid queryquery ] ]

EMPIEZA CON from SEGUIDO DE CERO

o MAS from o where

orderbyOPCIONA

LTERMINA CON UN

select o CON UN group by

PUEDE CONTINUAR CON UN

into

Page 16: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

Operaciones de Consulta de LINQOperaciones de Consulta de LINQ

RestricciónRestricción WhereWhere

ProyecciónProyección Select, SelectManySelect, SelectMany

OrdenaciónOrdenación OrderBy, ThenByOrderBy, ThenBy

AgrupaciónAgrupación GroupByGroupBy

CuantificaciónCuantificación Any, AllAny, All

ParticiónPartición Take, Skip, TakeWhile, SkipWhileTake, Skip, TakeWhile, SkipWhile

ConjuntosConjuntos Distinct, Union, Intersect, ExceptDistinct, Union, Intersect, Except

ElementosElementos First, FirstOrDefault, ElementAtFirst, FirstOrDefault, ElementAt

AgregaciónAgregación Count, Sum, Min, Max, Average, FoldCount, Sum, Min, Max, Average, Fold

ConversionConversion ToArray, ToList, ToDictionaryToArray, ToList, ToDictionary

CastingCasting OfType<T>OfType<T>

Page 17: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

Demostracion #3Demostracion #3

Usando métodos de consultaUsando métodos de consulta

Page 18: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

AgendaAgenda

Qué es LINQ?Qué es LINQ?

Standar Query OperationsStandar Query Operations

DLINQDLINQ

ConclusionesConclusiones

Page 19: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

Mapeo a través de atributosMapeo a través de atributosMapeo manual o automatico (built-in tool)Mapeo manual o automatico (built-in tool)

PersistenciaPersistenciaControl de cambios automáticoControl de cambios automático

DataContextDataContextBases de Datos fuertemente tipadasBases de Datos fuertemente tipadas

DLINQDLINQDatos Relacionales con DLINQDatos Relacionales con DLINQ

Page 20: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

Demostracion #3Demostracion #3

Accediendo a datos relacionales con Accediendo a datos relacionales con DLINQDLINQ

Page 21: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

CaracteristicasCaracteristicas

Language Integrated QueryLanguage Integrated QueryCheckeos en tiempo de compilación, Checkeos en tiempo de compilación, IntelliSenseIntelliSense

Sintaxsis tipo SQLSintaxsis tipo SQLSoporte para jerarquias y relacionesSoporte para jerarquias y relaciones

Carga de objetos inteligentesCarga de objetos inteligentesLazy o InmediataLazy o Inmediata

Page 22: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

Demostracion #4Demostracion #4

Relaciones con LINQRelaciones con LINQ

Page 23: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

CaracteristicasCaracteristicas

Updates automaticosUpdates automaticosUsando Usando optimistic concurrencyoptimistic concurrency

TransactionsTransactionsIntegradas con System.TransactionsIntegradas con System.Transactions

Page 24: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

Demostracion #5Demostracion #5

Updates usando DLINQUpdates usando DLINQ

Page 25: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

ConclusionesConclusiones

Page 26: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

Demostracion #7Demostracion #7

Poniendo todo junto….Poniendo todo junto….

Page 27: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

Para más informaciónPara más información

Data Access and Storage Developer Center: Data Access and Storage Developer Center: The The LINQLINQ Project Project

http://msdn.microsoft.com/netframework/future/linhttp://msdn.microsoft.com/netframework/future/linq/q/

C# 3.0 Hands On LabC# 3.0 Hands On Lab

LINQ Hands On LabLINQ Hands On Lab

http://staff.southworks.net/blogs/johnnyhttp://staff.southworks.net/blogs/johnny

http://www.ajlopez.nethttp://www.ajlopez.net

Page 28: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks

PreguntasPreguntas

Page 29: Language Integrated Query Johnny Halife Microsoft Student Ambassador Southworks