0
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 we...
Xml Relacional
• <note>
      <id>100</id>
      <to>1</to>
      <from>5</from>
      <heading>Reminder</heading>
      <...
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 compi...
Arquitetura
       C#                  VB.NET            Others


        .NET Language Integrated Query (LINQ)

         ...
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 SqlConn...
Com LINQ
•   public static IEnumerable GetMyData()
    {
      using (var myContext = new MyDataContext())
      {
       ...
LINQ to SQL
• // DataContext takes a connection string
  var db = new DataContext("c:northwindnorthwnd.mdf");

   // Get a...
Select / Where
• public void Linq1() {
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
      var lowNums =
        f...
Insert
Primary Key
public static bool EntityInsert(Entity entity) {
  try {
          var db = new DataClassesEzDataContex...
Update
• var dc = new BO.DataClassesEzDataContext();
• var user = Utils.User;
• user.password =
  Utils.Encript(passwordBo...
Delete
• Northwnd db = new Northwnd(@"c:Northwnd.mdf");
  // Query for a specific customer.
  var cust = (from c in db.Cus...
Inner Join
• var q =   from c in db.Funcionarios
            join o in db.Orders on
                    c. FuncionarioId e...
Transaction
•   System.Data.Common.DbTransaction trans = null;
•   var dc = new DataClassesUdescDataContext();

•   try {
...
Operadores
 Agregação     Conversão     Ordenação   Particionamento       Sets
Aggregate    Cast           OrderBy      Sk...
Performance
Performance
Performance
Performance
Performance
Dataset operation ADO vs LINQ
Customizações /Extensões
• namespace Palestra {
• partial class Aluno {
•    public string Faculdade() {
•      return "Ud...
LINQ com WebServices
• public static User[] UserSelectAll(){
•        var db = new DataClassesEzTimeDataContext();

•     ...
Serialização
• Padrão
• Unidirecional
LINQ to Entity
•   [Table(Name = "Employee")]
•     public class Employee
•     {
•       [Column(Name = "Id", DbType ="in...
Providers
• Relational data
  NHibernate, MySQL, Oracle, PostgreSQL
• Web services
  RDF, Flickr, Amazon, WebQueries
• Cus...
Alternativas
•   NHibernate
•   Castle MonoRail / ActiveRecord
•   SubSonic
•   Geradores de código + templates
    CodeSm...
LINQ - .NET FRAMEWORK 4.0
• Performance
• Usabilidade
    • Conversão automática de enumeradores
    • Associação com camp...
Perguntas
Linq
Upcoming SlideShare
Loading in...5
×

Linq

1,209

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
1,209
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
21
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Linq"

  1. 1. www.ez.inf.br
  2. 2. LINQ Fernando Magno | Vinicius Oliverio
  3. 3. Contexto • Amadurecimento da Orientação a Objetos • Tendência • Modelo Relacional
  4. 4. Xml • <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
  5. 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. 6. Xml Relacional • Informação pública • Web Semântica
  7. 7. Banco de Dados Relacional
  8. 8. 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
  9. 9. 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
  10. 10. Base de Desenvolvimento • .Net Framework 3 • Visual Studio 2005 ou superior • Sql Server 2005 Express ou superior- Freeware
  11. 11. 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; } } } }
  12. 12. Com LINQ • public static IEnumerable GetMyData() { using (var myContext = new MyDataContext()) { return myContext.Clients; } }
  13. 13. 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);
  14. 14. 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); } }
  15. 15. 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;} }
  16. 16. Update • var dc = new BO.DataClassesEzDataContext(); • var user = Utils.User; • user.password = Utils.Encript(passwordBoxNew.Password); • dc.Users.Attach(user, true); • dc.SubmitChanges();
  17. 17. 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();
  18. 18. 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;
  19. 19. 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(); • }
  20. 20. 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
  21. 21. Performance
  22. 22. Performance
  23. 23. Performance
  24. 24. Performance
  25. 25. Performance Dataset operation ADO vs LINQ
  26. 26. Customizações /Extensões • namespace Palestra { • partial class Aluno { • public string Faculdade() { • return "Udesc"; • } • } • }
  27. 27. LINQ com WebServices • public static User[] UserSelectAll(){ • var db = new DataClassesEzTimeDataContext(); • return db.Users.ToArray(); • }
  28. 28. Serialização • Padrão • Unidirecional
  29. 29. 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; • } • }
  30. 30. Providers • Relational data NHibernate, MySQL, Oracle, PostgreSQL • Web services RDF, Flickr, Amazon, WebQueries • Custom LDAP, Google Desktop, SharePoint, TerraServer maps
  31. 31. Alternativas • NHibernate • Castle MonoRail / ActiveRecord • SubSonic • Geradores de código + templates CodeSmith, MyGeneration, LLBLGen/Pro + NetTiers, DooDads.
  32. 32. 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)
  33. 33. Perguntas
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×