Thursday, May 21, 2009

Linq #1: Getting Started

這兩天花了一點時間大概看了一些What is Linq? Linq's design goal. Why Linq? History等不是很想看的東西。
With LINQ, Microsoft's intention was to provide a solution for the problem of object-relational mapping, as well as to simplify the interaction between objects and data sources.

這是我唯幾有畫的段落=    =,不知道究竟是不是個key。還是比較想來體驗一下code。
跟hello world一樣,首先要來個hello linq:


   1:  using System;

   2:  using System.Linq;

   3:   

   4:  static class HelloWorld

   5:  {

   6:    static void Main()

   7:    {

   8:      //先來個collection

   9:      string[] words = 

  10:         { "hello", "wonderful", "linq", "beautiful", "world" };

  11:      

  12:      //傳說中的linq語法在這from~ where~ select

  13:      var shortWords =   

  14:        from word in words

  15:        where word.Length <= 5

  16:        select word;

  17:   

  18:      //把剛剛處理好的資料印出來,結果就是: hello linq world 各一行

  19:      foreach (var word in shortWords)

  20:        Console.WriteLine(word);

  21:    }

  22:  }


Linq特別強調data query不再只是一串string,他變成是程式的一部份,所以你不會在執行程式時才發現sql下錯了、字拼錯、參數名字打錯這類的錯誤。Linq背後可存取的資料來源很多種,不管是存取資料庫或只是一個collection,只要學了Linq,就可以用統一的方法對這些資料來源進行存取。

再來一段長一點的,下面要表達的是,Linq也可以把資料弄成XML的樣子,重點是: 輕易地


   1:  using System;

   2:  using System.Linq;

   3:  using System.Xml;

   4:  using System.Xml.Linq;

   5:   

   6:  class Book

   7:  {

   8:    public string Publisher;

   9:    public string Title;

  10:    public int    Year;

  11:    public Book(string title, string publisher, int year)

  12:    {

  13:      Title = title;

  14:      Publisher = publisher;

  15:      Year = year;

  16:    }

  17:  }

  18:   

  19:  static class HelloLinqToXml

  20:  {

  21:    static void Main()

  22:    {

  23:        //用上面那個book class產生3筆資料

  24:        Book[] books = new Book[] {             

  25:        new Book("Ajax in Action", "Manning", 2005),

  26:        new Book("Windows Forms in Action", "Manning", 2006),

  27:        new Book("RSS and Atom in Action", "Manning", 2006)

  28:        };

  29:   

  30:      //重頭戲: 只能意會不能言傳XD

  31:      XElement xml = new XElement("books",  // layer1

  32:        from book in books

  33:        where book.Year == 2006

  34:        select new XElement("book",  //layer2

  35:          new XAttribute("title", book.Title),  // attribute of book(layer2)

  36:          new XElement("publisher", book.Publisher)  //layer3

  37:        )

  38:      );

  39:      Console.WriteLine(xml);

  40:   

  41:      //result:

  42:   

  43:          //<books>                                     ==> layer1

  44:          //  <book title="Windows Forms in Action">    ==> layer2 with attribute(title)

  45:          //    <publisher>Manning</publisher>          ==> layer3

  46:          //  </book>

  47:          //  <book title="RSS and Atom in Action">

  48:          //    <publisher>Manning</publisher>

  49:          //  </book>

  50:          //</books>

  51:    }

  52:  }


接下來應該是最常應用的: 連接資料庫


   1:  using System;

   2:  using System.Linq;

   3:  using System.Data.Linq;

   4:  using System.Data.Linq.Mapping;

   5:   

   6:  static class HelloLinqToSql

   7:  {

   8:     //declaring the classes to represent the application data: entities

   9:     //mapping object and database by adding customer attritube

  10:    [Table(Name="Contacts")]

  11:    class Contact

  12:    {

  13:      [Column(IsPrimaryKey=true)]

  14:      public int ContactID { get; set; }

  15:      [Column(Name="ContactName")]

  16:      public string Name { get; set; }

  17:      [Column]

  18:      public string City { get; set; }

  19:    }

  20:   

  21:    static void Main()

  22:    {

  23:      string path =   //使用northwind資料庫

  24:        System.IO.Path.GetFullPath(@"..\..\Data\northwnd.mdf");

  25:      //translate requests for objects into SQL queries

  26:      DataContext db = new DataContext(path);

  27:   

  28:      var contacts =                     

  29:        from contact in db.GetTable<Contact>()

  30:        where contact.City == "Paris"

  31:        select contact;

  32:   

  33:      foreach (var contact in contacts)        

  34:        Console.WriteLine("Bonjour "+contact.Name);

  35:    }

  36:  }


完畢。上面那一段程式,Linq做掉了一些東西:
  1. 連接資料庫
  2. 自動轉換SQL query
  3. 執行SQL

....如此一般如此一般.... 他其實還是有點複雜的...

Comments

0 Responses to "Linq #1: Getting Started"

Post a Comment

Tags