SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of SlickKnoldus Inc.
 
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 185Mahmoud Samir Fayed
 
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 AnalyticsDave Stokes
 
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 181Mahmoud Samir Fayed
 
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 MySQLDave Stokes
 
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legione-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 196Mahmoud Samir Fayed
 
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...DataStax
 
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 88Mahmoud Samir Fayed
 
Validating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationValidating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationDave Stokes
 
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 ...MongoDB
 
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 WhiteSencha
 
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 OptionPriya Rajagopal
 
Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)MongoDB
 
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 ...Dave Stokes
 

Was ist angesagt? (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 ...
 

Andere mochten auch

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 literaturemlodenbach
 
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 literaturemlodenbach
 
Sinterklaas bezoekt Romae, achter de schermen
Sinterklaas bezoekt Romae, achter de schermenSinterklaas bezoekt Romae, achter de schermen
Sinterklaas bezoekt Romae, achter de schermenRomae internet en content
 
Counting adventure
Counting adventureCounting adventure
Counting adventuremlodenbach
 
Night world (1)
Night world (1)Night world (1)
Night world (1)mlodenbach
 
Touching spirit bear
Touching spirit bearTouching spirit bear
Touching spirit bearmlodenbach
 
The hero’s journey
The hero’s journeyThe hero’s journey
The hero’s journeymlodenbach
 
Homeostasis
HomeostasisHomeostasis
Homeostasiserichemo
 
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 Lifecyclevfandco
 
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 Professionalsvfandco
 

Andere mochten auch (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
 

Ähnlich wie Linq

LINQ-Introduction.ppt
LINQ-Introduction.pptLINQ-Introduction.ppt
LINQ-Introduction.pptssusera8c91a
 
Introduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIRIntroduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIRPeter Elst
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldChristian Melchior
 
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#Vagif Abilov
 
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...Fons Sonnemans
 
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...dotNet Miami
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programmingchhaichivon
 
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 UnicornsRichie Rump
 
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 ConsumersJerod Johnson
 
Marmagna desai
Marmagna desaiMarmagna desai
Marmagna desaijmsthakur
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracleyazidds2
 
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 RavenDBOren Eini
 
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 JDBCOUM SAOKOSAL
 
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 WolffJAX London
 

Ähnlich wie 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
 

Mehr von 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ãesEasy 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
 

Mehr von 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
 

Kürzlich hochgeladen

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 

Kürzlich hochgeladen (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

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)