SlideShare a Scribd company logo
1 of 34
Download to read offline
www.ez.inf.br
LINQ
Fernando Magno | Vinicius Oliverio
Contexto
• Amadurecimento da Orientação a Objetos
• Tendência
• Modelo Relacional
Xml
• <note>
     <to>Tove</to>
     <from>Jani</from>
     <heading>Reminder</heading>
     <body>Don't forget me this weekend!</body>
  </note>
Xml Relacional
• <note>
      <id>100</id>
      <to>1</to>
      <from>5</from>
      <heading>Reminder</heading>
      <body>Don't forget me this weekend!</body>
  </note>
  <person>
      <id>1</id>
      <name>Tove</name>
      <age>22</age>
  </person>
Xml Relacional
• Informação pública
• Web Semântica
Banco de Dados Relacional
LINQ – .NET Language Integrated
                Query
• Consulta integrada
  –   Metadados
  –   Sintaxe em tempo de compilação
  –   Tipagem estática
  –   IntelliSense
• Operadores
  – Padrão
  – Customizáveis
       • avaliação remota, tradução de consultas, otimização, etc
Arquitetura
       C#                  VB.NET            Others


        .NET Language Integrated Query (LINQ)

                LINQ data source providers
                ADO.NET support for LINQ
   LINQ         LINQ         LINQ       LINQ        LINQ
to Objects   to Datasets    to SQL   to Entities   to XML
Base de Desenvolvimento
• .Net Framework 3
• Visual Studio 2005 ou superior
• Sql Server 2005 Express ou superior- Freeware
Programação Sem LINQ
•   public static IEnumerable GetMyData()
    {
      using (SqlConnection myConnection = new SqlConnection(myConnectionString))
      {
        using (SqlCommand myCommand = myConnection.CreateCommand())
        {
          myCommand.CommandText = "SELECT * FROM dbo.myTable";
                using (SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand))
                {
                  DataTable resultTable = new DataTable();
                    myAdapter.Fill(resultTable);
                    return resultTable.Rows;
                }
            }
        }
    }
Com LINQ
•   public static IEnumerable GetMyData()
    {
      using (var myContext = new MyDataContext())
      {
        return myContext.Clients;
      }
    }
LINQ to SQL
• // DataContext takes a connection string
  var db = new DataContext("c:northwindnorthwnd.mdf");

   // Get a typed table to run queries
   Table<Customer> Customers = db.GetTable<Customer>();

   // Query for customers from London
   var q = from c in Customers where c.City == "London" select c;

   foreach (var cust in q)
        Console.WriteLine(“City = {0}“, cust.City);
Select / Where
• public void Linq1() {
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
      var lowNums =
        from n in numbers
        where n < 5
        select n;
      Console.WriteLine("Numbers < 5:");
          foreach (var x in lowNums) {
                 Console.WriteLine(x);
      }
  }
Insert
Primary Key
public static bool EntityInsert(Entity entity) {
  try {
          var db = new DataClassesEzDataContext();
          db.Entities.InsertOnSubmit(entity);
          db.SubmitChanges();
          return true;
  }
  catch {return false;}
}
Update
• var dc = new BO.DataClassesEzDataContext();
• var user = Utils.User;
• user.password =
  Utils.Encript(passwordBoxNew.Password);
• dc.Users.Attach(user, true);
• dc.SubmitChanges();
Delete
• Northwnd db = new Northwnd(@"c:Northwnd.mdf");
  // Query for a specific customer.
  var cust = (from c in db.Customers where c.CustomerID == "ALFKI" select
  c).First();

   // Removing it from the table also removes it from the Customer’s list.
   db.Orders.DeleteOnSubmit(cust);

   // Ask the DataContext to save all the changes.
    db.SubmitChanges();
Inner Join
• var q =   from c in db.Funcionarios
            join o in db.Orders on
                    c. FuncionarioId equals o.FuncionarioId
            where c.Cidade == “Joinville"
            select o;
Transaction
•   System.Data.Common.DbTransaction trans = null;
•   var dc = new DataClassesUdescDataContext();

•   try {
•                 dc.Connection.Open();
•                 trans = dc.Connection.BeginTransaction();
•                 dc.Transaction = trans;
•                 //...
•                 trans.Commit();
•   }
•   catch {
•                 if (trans != null) trans.Rollback();
•           }
•   finally {
•                 // Close the connection
•                 if (objDataClass.Connection.State == ConnectionState.Open)
•                    objDataClass.Connection.Close();
•             }
Operadores
 Agregação     Conversão     Ordenação   Particionamento       Sets
Aggregate    Cast           OrderBy      Skip              Concat
Average      OfType         ThenBy       SkipWhile         Distinct
Count        ToArray        Descending   Take              Except
Max          ToDictionary   Reverse      TakeWhile         Intersect
Min          ToList                                        Union
Sum          ToLookup
             ToSequence
Performance
Performance
Performance
Performance
Performance
Dataset operation ADO vs LINQ
Customizações /Extensões
• namespace Palestra {
• partial class Aluno {
•    public string Faculdade() {
•      return "Udesc";
•    }
• }
• }
LINQ com WebServices
• public static User[] UserSelectAll(){
•        var db = new DataClassesEzTimeDataContext();

•          return db.Users.ToArray();
•      }
Serialização
• Padrão
• Unidirecional
LINQ to Entity
•   [Table(Name = "Employee")]
•     public class Employee
•     {
•       [Column(Name = "Id", DbType ="int not null", IsPrimaryKey = true, IsDbGenerated = true )]
•       public int Id
•       {
•          get;
•          set;
•       }

•         [Column(Name = "Name", DbType = "NVarChar(200) NOT NULL")]
•         public String Name
•         {
•           get;
•           set;
•         }
•     }
Providers
• Relational data
  NHibernate, MySQL, Oracle, PostgreSQL
• Web services
  RDF, Flickr, Amazon, WebQueries
• Custom
  LDAP, Google Desktop, SharePoint,
  TerraServer maps
Alternativas
•   NHibernate
•   Castle MonoRail / ActiveRecord
•   SubSonic
•   Geradores de código + templates
    CodeSmith, MyGeneration, LLBLGen/Pro +
    NetTiers, DooDads.
LINQ - .NET FRAMEWORK 4.0
• Performance
• Usabilidade
    • Conversão automática de enumeradores
    • Associação com campo que não seja chave primária
    • Herança
• Query Stability
    • Auto referência não causa estouro de pilha.
•   Update Stability
•   General Stability
•   SQL Metal
•   LINQ do SQL class designer
•   Code Generation (SQL Metal + LINQ to SQL Class Designer)
Perguntas

More Related Content

What's hot

What's hot (20)

Green dao
Green daoGreen dao
Green dao
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of Slick
 
greenDAO
greenDAOgreenDAO
greenDAO
 
The Ring programming language version 1.5.4 book - Part 28 of 185
The Ring programming language version 1.5.4 book - Part 28 of 185The Ring programming language version 1.5.4 book - Part 28 of 185
The Ring programming language version 1.5.4 book - Part 28 of 185
 
Green dao
Green daoGreen dao
Green dao
 
Data Love Conference - Window Functions for Database Analytics
Data Love Conference - Window Functions for Database AnalyticsData Love Conference - Window Functions for Database Analytics
Data Love Conference - Window Functions for Database Analytics
 
The Ring programming language version 1.5.2 book - Part 27 of 181
The Ring programming language version 1.5.2 book - Part 27 of 181The Ring programming language version 1.5.2 book - Part 27 of 181
The Ring programming language version 1.5.2 book - Part 27 of 181
 
Discover the Power of the NoSQL + SQL with MySQL
Discover the Power of the NoSQL + SQL with MySQLDiscover the Power of the NoSQL + SQL with MySQL
Discover the Power of the NoSQL + SQL with MySQL
 
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
 
The Ring programming language version 1.7 book - Part 41 of 196
The Ring programming language version 1.7 book - Part 41 of 196The Ring programming language version 1.7 book - Part 41 of 196
The Ring programming language version 1.7 book - Part 41 of 196
 
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
 
The Ring programming language version 1.3 book - Part 19 of 88
The Ring programming language version 1.3 book - Part 19 of 88The Ring programming language version 1.3 book - Part 19 of 88
The Ring programming language version 1.3 book - Part 19 of 88
 
Validating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationValidating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentation
 
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
 
SenchaCon 2016: The Once and Future Grid - Nige White
SenchaCon 2016: The Once and Future Grid - Nige WhiteSenchaCon 2016: The Once and Future Grid - Nige White
SenchaCon 2016: The Once and Future Grid - Nige White
 
Core Data Migrations and A Better Option
Core Data Migrations and A Better OptionCore Data Migrations and A Better Option
Core Data Migrations and A Better Option
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
 
Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)
 
Thunderstruck
ThunderstruckThunderstruck
Thunderstruck
 
Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...
Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...
Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...
 

Viewers also liked

Results from lifting a line from literature
Results from lifting a line from literatureResults from lifting a line from literature
Results from lifting a line from literature
mlodenbach
 
Results from lifting a line from literature
Results from lifting a line from literatureResults from lifting a line from literature
Results from lifting a line from literature
mlodenbach
 
Night world (1)
Night world (1)Night world (1)
Night world (1)
mlodenbach
 
Touching spirit bear
Touching spirit bearTouching spirit bear
Touching spirit bear
mlodenbach
 
The hero’s journey
The hero’s journeyThe hero’s journey
The hero’s journey
mlodenbach
 
Homeostasis
HomeostasisHomeostasis
Homeostasis
erichemo
 
Do It Yourself Outplacement Kit For Hr Professionals
Do It Yourself Outplacement Kit For Hr ProfessionalsDo It Yourself Outplacement Kit For Hr Professionals
Do It Yourself Outplacement Kit For Hr Professionals
vfandco
 

Viewers also liked (19)

Memòria RAM
Memòria RAMMemòria RAM
Memòria RAM
 
Easy Portfolio
Easy PortfolioEasy Portfolio
Easy Portfolio
 
Apresentacao silverlight
Apresentacao silverlightApresentacao silverlight
Apresentacao silverlight
 
Praktische handvatten voor effectief MVO
Praktische handvatten voor effectief MVOPraktische handvatten voor effectief MVO
Praktische handvatten voor effectief MVO
 
Results from lifting a line from literature
Results from lifting a line from literatureResults from lifting a line from literature
Results from lifting a line from literature
 
Sinterklaas bezoekt Romae
Sinterklaas bezoekt RomaeSinterklaas bezoekt Romae
Sinterklaas bezoekt Romae
 
Grijsgesurfd
GrijsgesurfdGrijsgesurfd
Grijsgesurfd
 
Results from lifting a line from literature
Results from lifting a line from literatureResults from lifting a line from literature
Results from lifting a line from literature
 
Sinterklaas bezoekt Romae, achter de schermen
Sinterklaas bezoekt Romae, achter de schermenSinterklaas bezoekt Romae, achter de schermen
Sinterklaas bezoekt Romae, achter de schermen
 
ICT en klimaatverandering
ICT en klimaatveranderingICT en klimaatverandering
ICT en klimaatverandering
 
Counting adventure
Counting adventureCounting adventure
Counting adventure
 
Night world (1)
Night world (1)Night world (1)
Night world (1)
 
Touching spirit bear
Touching spirit bearTouching spirit bear
Touching spirit bear
 
The hero’s journey
The hero’s journeyThe hero’s journey
The hero’s journey
 
Homeostasis
HomeostasisHomeostasis
Homeostasis
 
Finance Transformation
Finance TransformationFinance Transformation
Finance Transformation
 
Designing HR\'s Greatest Impact At Each Stage Of The Corporate Lifecycle
Designing HR\'s Greatest Impact At Each Stage Of The Corporate LifecycleDesigning HR\'s Greatest Impact At Each Stage Of The Corporate Lifecycle
Designing HR\'s Greatest Impact At Each Stage Of The Corporate Lifecycle
 
Do It Yourself Outplacement Kit For Hr Professionals
Do It Yourself Outplacement Kit For Hr ProfessionalsDo It Yourself Outplacement Kit For Hr Professionals
Do It Yourself Outplacement Kit For Hr Professionals
 
Palanques
PalanquesPalanques
Palanques
 

Similar to Linq

Entity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsEntity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic Unicorns
Richie Rump
 

Similar to Linq (20)

Couchbas for dummies
Couchbas for dummiesCouchbas for dummies
Couchbas for dummies
 
LINQ-Introduction.ppt
LINQ-Introduction.pptLINQ-Introduction.ppt
LINQ-Introduction.ppt
 
Introduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIRIntroduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIR
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected World
 
Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#
 
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...
 
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
 
Entity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsEntity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic Unicorns
 
Naver_alternative_to_jpa
Naver_alternative_to_jpaNaver_alternative_to_jpa
Naver_alternative_to_jpa
 
Orms vs Micro-ORMs
Orms vs Micro-ORMsOrms vs Micro-ORMs
Orms vs Micro-ORMs
 
SQL for Web APIs - Simplifying Data Access for API Consumers
SQL for Web APIs - Simplifying Data Access for API ConsumersSQL for Web APIs - Simplifying Data Access for API Consumers
SQL for Web APIs - Simplifying Data Access for API Consumers
 
Marmagna desai
Marmagna desaiMarmagna desai
Marmagna desai
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
Lessons from the Trenches - Building Enterprise Applications with RavenDB
Lessons from the Trenches - Building Enterprise Applications with RavenDBLessons from the Trenches - Building Enterprise Applications with RavenDB
Lessons from the Trenches - Building Enterprise Applications with RavenDB
 
Google cloud Dataflow & Apache Flink
Google cloud Dataflow & Apache FlinkGoogle cloud Dataflow & Apache Flink
Google cloud Dataflow & Apache Flink
 
Python with MySql.pptx
Python with MySql.pptxPython with MySql.pptx
Python with MySql.pptx
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
 
B_110500002
B_110500002B_110500002
B_110500002
 

More from Easy Communication & Technology

Análise e Projeto de Sistemas - Coleira automatizada para cães
Análise e Projeto de Sistemas - Coleira automatizada para cãesAnálise e Projeto de Sistemas - Coleira automatizada para cães
Análise e Projeto de Sistemas - Coleira automatizada para cães
Easy Communication & Technology
 
Fernando Alves Michalak Análise de Problemas Paralelizaveis.
Fernando Alves Michalak Análise de Problemas Paralelizaveis.Fernando Alves Michalak Análise de Problemas Paralelizaveis.
Fernando Alves Michalak Análise de Problemas Paralelizaveis.
Easy Communication & Technology
 
Paralelização do Corte de Superficies com Algoritmo Genético
Paralelização do Corte de Superficies com Algoritmo Genético Paralelização do Corte de Superficies com Algoritmo Genético
Paralelização do Corte de Superficies com Algoritmo Genético
Easy Communication & Technology
 

More from Easy Communication & Technology (19)

Easy - Apresentação Institucional
Easy - Apresentação InstitucionalEasy - Apresentação Institucional
Easy - Apresentação Institucional
 
A imprensa e os desafios da mídia social
A imprensa e os desafios da mídia socialA imprensa e os desafios da mídia social
A imprensa e os desafios da mídia social
 
Manufatura
ManufaturaManufatura
Manufatura
 
Empreendedorismo
EmpreendedorismoEmpreendedorismo
Empreendedorismo
 
Easy Manager
Easy ManagerEasy Manager
Easy Manager
 
Redes depetri
Redes depetriRedes depetri
Redes depetri
 
Web m
Web mWeb m
Web m
 
Niilismo
NiilismoNiilismo
Niilismo
 
Toyotismo – lean manufact
Toyotismo – lean manufactToyotismo – lean manufact
Toyotismo – lean manufact
 
Setup de computadores
Setup de computadoresSetup de computadores
Setup de computadores
 
Análise e Projeto de Sistemas - Coleira automatizada para cães
Análise e Projeto de Sistemas - Coleira automatizada para cãesAnálise e Projeto de Sistemas - Coleira automatizada para cães
Análise e Projeto de Sistemas - Coleira automatizada para cães
 
Coleira automatizada para cães
Coleira automatizada para cãesColeira automatizada para cães
Coleira automatizada para cães
 
Fernando Alves Michalak Análise de Problemas Paralelizaveis.
Fernando Alves Michalak Análise de Problemas Paralelizaveis.Fernando Alves Michalak Análise de Problemas Paralelizaveis.
Fernando Alves Michalak Análise de Problemas Paralelizaveis.
 
Classificacao de Aplicativos de Modelagem
Classificacao de Aplicativos de ModelagemClassificacao de Aplicativos de Modelagem
Classificacao de Aplicativos de Modelagem
 
Paralelização do Corte de Superficies com Algoritmo Genético
Paralelização do Corte de Superficies com Algoritmo Genético Paralelização do Corte de Superficies com Algoritmo Genético
Paralelização do Corte de Superficies com Algoritmo Genético
 
Udesc 2009
Udesc 2009Udesc 2009
Udesc 2009
 
Silverlight
SilverlightSilverlight
Silverlight
 
ApresentaçãO Ez
ApresentaçãO EzApresentaçãO Ez
ApresentaçãO Ez
 
Diagrama
DiagramaDiagrama
Diagrama
 

Recently uploaded

Breaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdfBreaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
UK Journal
 

Recently uploaded (20)

Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
Designing for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at ComcastDesigning for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at Comcast
 
Microsoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireMicrosoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - Questionnaire
 
Easier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties ReimaginedEasier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties Reimagined
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024
 
Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdfBreaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage Intacct
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 

Linq

  • 2. LINQ Fernando Magno | Vinicius Oliverio
  • 3. Contexto • Amadurecimento da Orientação a Objetos • Tendência • Modelo Relacional
  • 4. Xml • <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
  • 5. Xml Relacional • <note> <id>100</id> <to>1</to> <from>5</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> <person> <id>1</id> <name>Tove</name> <age>22</age> </person>
  • 6. Xml Relacional • Informação pública • Web Semântica
  • 7. Banco de Dados Relacional
  • 8.
  • 9. LINQ – .NET Language Integrated Query • Consulta integrada – Metadados – Sintaxe em tempo de compilação – Tipagem estática – IntelliSense • Operadores – Padrão – Customizáveis • avaliação remota, tradução de consultas, otimização, etc
  • 10. Arquitetura C# VB.NET Others .NET Language Integrated Query (LINQ) LINQ data source providers ADO.NET support for LINQ LINQ LINQ LINQ LINQ LINQ to Objects to Datasets to SQL to Entities to XML
  • 11. Base de Desenvolvimento • .Net Framework 3 • Visual Studio 2005 ou superior • Sql Server 2005 Express ou superior- Freeware
  • 12. Programação Sem LINQ • public static IEnumerable GetMyData() { using (SqlConnection myConnection = new SqlConnection(myConnectionString)) { using (SqlCommand myCommand = myConnection.CreateCommand()) { myCommand.CommandText = "SELECT * FROM dbo.myTable"; using (SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand)) { DataTable resultTable = new DataTable(); myAdapter.Fill(resultTable); return resultTable.Rows; } } } }
  • 13. Com LINQ • public static IEnumerable GetMyData() { using (var myContext = new MyDataContext()) { return myContext.Clients; } }
  • 14. LINQ to SQL • // DataContext takes a connection string var db = new DataContext("c:northwindnorthwnd.mdf"); // Get a typed table to run queries Table<Customer> Customers = db.GetTable<Customer>(); // Query for customers from London var q = from c in Customers where c.City == "London" select c; foreach (var cust in q) Console.WriteLine(“City = {0}“, cust.City);
  • 15. Select / Where • public void Linq1() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var lowNums = from n in numbers where n < 5 select n; Console.WriteLine("Numbers < 5:"); foreach (var x in lowNums) { Console.WriteLine(x); } }
  • 16. Insert Primary Key public static bool EntityInsert(Entity entity) { try { var db = new DataClassesEzDataContext(); db.Entities.InsertOnSubmit(entity); db.SubmitChanges(); return true; } catch {return false;} }
  • 17. Update • var dc = new BO.DataClassesEzDataContext(); • var user = Utils.User; • user.password = Utils.Encript(passwordBoxNew.Password); • dc.Users.Attach(user, true); • dc.SubmitChanges();
  • 18. Delete • Northwnd db = new Northwnd(@"c:Northwnd.mdf"); // Query for a specific customer. var cust = (from c in db.Customers where c.CustomerID == "ALFKI" select c).First(); // Removing it from the table also removes it from the Customer’s list. db.Orders.DeleteOnSubmit(cust); // Ask the DataContext to save all the changes. db.SubmitChanges();
  • 19. Inner Join • var q = from c in db.Funcionarios join o in db.Orders on c. FuncionarioId equals o.FuncionarioId where c.Cidade == “Joinville" select o;
  • 20. Transaction • System.Data.Common.DbTransaction trans = null; • var dc = new DataClassesUdescDataContext(); • try { • dc.Connection.Open(); • trans = dc.Connection.BeginTransaction(); • dc.Transaction = trans; • //... • trans.Commit(); • } • catch { • if (trans != null) trans.Rollback(); • } • finally { • // Close the connection • if (objDataClass.Connection.State == ConnectionState.Open) • objDataClass.Connection.Close(); • }
  • 21. Operadores Agregação Conversão Ordenação Particionamento Sets Aggregate Cast OrderBy Skip Concat Average OfType ThenBy SkipWhile Distinct Count ToArray Descending Take Except Max ToDictionary Reverse TakeWhile Intersect Min ToList Union Sum ToLookup ToSequence
  • 27. Customizações /Extensões • namespace Palestra { • partial class Aluno { • public string Faculdade() { • return "Udesc"; • } • } • }
  • 28. LINQ com WebServices • public static User[] UserSelectAll(){ • var db = new DataClassesEzTimeDataContext(); • return db.Users.ToArray(); • }
  • 30. LINQ to Entity • [Table(Name = "Employee")] • public class Employee • { • [Column(Name = "Id", DbType ="int not null", IsPrimaryKey = true, IsDbGenerated = true )] • public int Id • { • get; • set; • } • [Column(Name = "Name", DbType = "NVarChar(200) NOT NULL")] • public String Name • { • get; • set; • } • }
  • 31. Providers • Relational data NHibernate, MySQL, Oracle, PostgreSQL • Web services RDF, Flickr, Amazon, WebQueries • Custom LDAP, Google Desktop, SharePoint, TerraServer maps
  • 32. Alternativas • NHibernate • Castle MonoRail / ActiveRecord • SubSonic • Geradores de código + templates CodeSmith, MyGeneration, LLBLGen/Pro + NetTiers, DooDads.
  • 33. LINQ - .NET FRAMEWORK 4.0 • Performance • Usabilidade • Conversão automática de enumeradores • Associação com campo que não seja chave primária • Herança • Query Stability • Auto referência não causa estouro de pilha. • Update Stability • General Stability • SQL Metal • LINQ do SQL class designer • Code Generation (SQL Metal + LINQ to SQL Class Designer)