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

Linq

  • 1.
  • 2.
    LINQ Fernando Magno |Vinicius Oliverio
  • 3.
    Contexto • Amadurecimento daOrientaçã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çãopública • Web Semântica
  • 7.
    Banco de DadosRelacional
  • 9.
    LINQ – .NETLanguage 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 staticbool 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 • varq = 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
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
    Customizações /Extensões • namespacePalestra { • partial class Aluno { • public string Faculdade() { • return "Udesc"; • } • } • }
  • 28.
    LINQ com WebServices •public static User[] UserSelectAll(){ • var db = new DataClassesEzTimeDataContext(); • return db.Users.ToArray(); • }
  • 29.
  • 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 - .NETFRAMEWORK 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)
  • 34.