1 / 43

LINQ (.NET Language Integrated Query)

LINQ (.NET Language Integrated Query). Mục lục. Giới thiệu Microsoft.NET Framework 3.5 ---- Đặt vấn đề Linq Định nghĩa – Tính chất – Mục đích – Triển khai Sơ lược và các cấu trúc đặc tả Truy vấn dữ liệu đối tượng trong bộ nhớ Truy vấn CSDL “ thực ” Truy vấn tập tin

ebony
Télécharger la présentation

LINQ (.NET Language Integrated Query)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. LINQ (.NET Language Integrated Query)

  2. Mục lục • Giớithiệu Microsoft.NET Framework 3.5 ---- • Đặtvấnđề • Linq • Địnhnghĩa – Tínhchất – Mụcđích – Triểnkhai • Sơlượcvàcáccấutrúcđặctả • Truyvấndữliệuđốitượngtrongbộnhớ • Truyvấn CSDL “thực” • Truyvấntập tin • Truyvấn CSDL quanhệ • Truyvấn XML • Tàiliệuthamkhảo • Lờicámơn

  3. Giới thiệu Microsoft .NET FrameWork 3.5 Làphiênbảnthứ 5 của Microsoft .NET Framework Microsoft Visual Studio 2008 • Cho phépxâydựngứngdụnglinhđộng, kếtnốivàthựcthimọinơi: • Thiếtbịdiđộng • Desktops • Servers .NET Framework 3.5 .NET Framework 3.0 SP1 .NET Framework 2.0 SP1 • Bộmôn HTTT

  4. Giới thiệu Microsoft .NET FrameWork 3.5 Language Integrated Query (LINQ) and data awareness ASP.NET AJAX support for Web 2.0-style applications New Web protocols in WCF Exposing WF workflows as WCF services Full tooling support in Visual Studio 2008 for WF, WCF, and WPF .NET FRAMEWORK Windows Workflow Foundation (WF) Windows Presentation Foundation (WPF) Windows Cardspace Windows Communication Foundation (WCF) • Bộmôn HTTT

  5. Objects Đặt vấn đề “Bermuda Triangle of data processing” Relations XML Nguyênnhân:Data != Object Lậptrìnhviênphảinhọccông “hàngắn” haithựcthểnàyvớinhautrongmỗidựánphầnmềm • Bộmôn HTTT

  6. LINQ – Định nghĩa • Làthưviệnmởrộngchocácngônngữlậptrình C# và VB.NET (cóthểmởrộngchocácngônngữkhác) cungcấpkhảnăngtruyvấnđồngnhất, trựctiếpdữliệuđốitượng, CSDL, và XML • Kháiniệmtruyvấn: • Thaotácvớidữliệu, ánhxạgiữacácmôhìnhdữliệu. • Sựtươngtácvớidữliệunàythông qua cáccâulệnhcócúphápnhưcúphápcáccâutruyvấntrong SQL (Xinđượcgiảithíchrõ ở cácphầnsau) • Bộmôn HTTT

  7. LINQ – Tính chất • Thaotácnhanhchóngthaotácvớidữliệu • Đồngnhấtcácxửlý, cáctruyvấnvớicácdữliệukhácnhau • Linhđộngtrongxâydựngcácxửlý, cáctruyvấn. • Ánhxạnhanh, tốtgiữacácmôhìnhdữliệu • Tốcđộxửlýnhanh, bảomật • Khảnăngkiểmlỗivàbáolỗi (report) trongquátrìnhtruyvấn • Bộmôn HTTT

  8. LINQ – Mục đích • Giảmthờigianlãngphíkhitruyvấndữliệu • Giảmkhảnăngđụngđộgiữacác APIs Providers củacácloạidữliệukhácnhau • Nhanhchóngchuyểnđổicácmôhìnhdữliệu • Mởrộngkhảnăngxửlýtruyvấn • Bộmôn HTTT

  9. LINQ – Triển khai • Ápdụngnhanhvàocácdựántrênmôitrường .NET • Win Application • Web Application • Mobile Application • Cóthểmởrộnghỗtrợchocácngônngữlậptrìnhkhác (ngoài .NET) • Bộmôn HTTT

  10. LINQ - Mô hình • Bộmôn HTTT

  11. LINQ – Sơ lược LINQ C# • using System; • using System.Linq; • static class HelloWorld • { • static void Main() • { • string[] words = • { "hello", "wonderful", "linq", "beautiful", "world" }; • var shortWords = • from word in words • where word.Length <= 5 • select word; • foreach (var word in shortWords) • Console.WriteLine(word); • } • } • using System; • static class HelloWorld • { • static void Main() • { • string[] words = new string[] { • "hello", "wonderful", "linq", "beautiful", "world" }; • foreach (string word in words) • { • if (word.Length <= 5) • Console.WriteLine(word); • } • } • } • Bộmôn HTTT

  12. LINQ – Các cấu trúc đặc tả Query expressions var contacts = from c in customers where c.City == "Hove" select new { c.Name, c.Phone }; Local variable type inference Lambda expressions var contacts = customers .Where(c => c.City == "Hove") .Select(c => new { c.Name, c.Phone }); Extension methods Object initializers Anonymous types • Bộmôn HTTT

  13. LINQ – Query expressions Language integrated query syntax from id in source { from id in source | where condition } [ orderby ordering, ordering, …] select expr | group expr by key [ into id query ] • Bộmôn HTTT

  14. LINQ – Local variable type inference • Bộmôn HTTT

  15. LINQ – Extension methods • Bộmôn HTTT

  16. LINQ – Anonymous types • Bộmôn HTTT

  17. LINQ – Object initializers • Bộmôn HTTT

  18. LINQ – Lambda expressions • Bộmôn HTTT

  19. LINQ – Kiến trúc • Bộmôn HTTT

  20. Mục lục • Giớithiệu Microsoft.NET Framework 3.5 • Đặtvấnđề • Linq • Địnhnghĩa – Tínhchất – Mụcđích – Triểnkhai • Sơlượcvàcáccấutrúcđặctả • Truyvấndữliệuđốitượngtrongbộnhớ----- • Truyvấn CSDL “thực” • Truyvấntập tin • Truyvấn CSDL quanhệ • Truyvấn XML • Tàiliệuthamkhảo • Lờicámơn

  21. LINQ – Truy vấn dữ liệu đối tượng trong bộ nhớ Vídụ 2 Vídụ 1 GridView1.DataSource = from book in SampleData.Books where book.Title.Length > 10 orderby book.Price select book; GridView1.DataBind(); • using System; • static class HelloWorld • { • static void Main() • { • string[] words = new string[] { • "hello", "wonderful", "linq", "beautiful", "world" }; • foreach (string word in words) • { • if (word.Length <= 5) • Console.WriteLine(word); • } • } • } • Bộmôn HTTT

  22. LINQ – Truy vấn dữ liệu đối tượng trong bộ nhớ Vídụ 3 static double Square(double n) { Console.WriteLine("Computing Square("+n+")..."); return Math.Pow(n, 2); } int[] numbers = {1, 2, 3}; var query = from n in numbers select Square(n); foreach (var n in query) Console.WriteLine(n); for (int i = 0; i < numbers.Length; i++) numbers[i] = numbers[i]+10; foreach (var n in query) Console.WriteLine(n); Kếtquả: Computing Square(1)... 1 Computing Square(2)... 4 Computing Square(3)... 9 - Collection updated - Computing Square(11)... 121 Computing Square(12)... 144 Computing Square(13)... 169 • Bộmôn HTTT

  23. Mục lục • Giớithiệu Microsoft.NET Framework 3.5 • Đặtvấnđề • Linq • Địnhnghĩa – Tínhchất – Mụcđích – Triểnkhai • Sơlượcvàcáccấutrúcđặctả • Truyvấndữliệuđốitượngtrongbộnhớ • Truyvấn CSDL “thực” • Truyvấntập tin ----- • Truyvấn CSDL quanhệ • Truyvấn XML • Tàiliệuthamkhảo • Lờicámơn

  24. LINQ – Truy vấn tập tin Vídụ 2 Vídụ 1 Var books= from line in File.ReadAllLines("books.csv") where !line.StartsWith("#") let parts = line.Split(',') select new { Isbn=parts[0], Title=parts[1], Publisher=parts[3] }; using (StreamReader reader = new StreamReader("books.csv")) { var books = from line in reader.Lines() where !line.StartsWith("#") let parts = line.Split(',') select new { Title=parts[1], Publisher=parts[3], Isbn=parts[0] } //………… } • Bộmôn HTTT

  25. LINQ – Truy vấn CSDL quan hệ(System.Data.Linq) • DLINQ: • Là bộ hàm thư viện API dùng để truy vấn CSDL quan hệ (SQL) • Là tập các lớp đặc biệt cho phép thể hiện các bảng và hàng dữ liệu theo dạng đối tượng. Do vậy có thể truy vấn trực tiếp CSDL thông qua LINQ • Dùng đối tượng DataContext để mở kết nối đến CSDL. Sau đó dùng lớp Table<> để thể hiện bảng dữ liệu, và với đối tượng này, chúng ta có thể sử dụng cú pháp LINQ để truy vấn. • Bộmôn HTTT

  26. LINQ – Truy vấn CSDL quan hệ(System.Data.Linq) • Bộmôn HTTT

  27. LINQ – Truyvấn CSDL quanhệ(System.Data.Linq) Vídụ 1 – Đọcdữliệu Example (SQL) create table Orders ( OrderID nvarchar(32) primary key not null, Customer nvarchar(32) not null, Amount int ) • Example (C#) • [Table(Name="Orders")] • public class Order { • [Column(DbType="nvarchar(32) not null", Id=true)] • public string OrderID; • [Column(DbType="nvarchar(32) not null")] • public string Customer; • [Column] • public int Amount; • } • Bộmôn HTTT

  28. LINQ – Truyvấn CSDL quanhệ(System.Data.Linq) Vídụ 1 – Đọcdữliệu • DataContext context = new DataContext("Initial Catalog=petdb;IntegratedSecurity=sspi"); • Table<Person> custs = context.GetTable<Person>(); • Table<Order> orders = context.GetTable<Order>(); • var query = from c in custs, o in orders • where o.Customer == c.Name • select new { • c.Name, • o.OrderID, • o.Amount, • } • foreach (var item in query) • Console.WriteLine("{0} {1} {2} {3}", item.Name, item.OrderID, item.Amount, item.Age); SELECT [t0].[Age], [t1].[Amount], [t0].[Name] , c.Age [t1].[OrderID] [FROM [Customers] AS [t0], [Orders] AS [t1] WHERE [t1].[Customer] = [t0].[Name] • Bộmôn HTTT

  29. LINQ – Truyvấn CSDL quanhệ(System.Data.Linq) Vídụ 2 –Cậpnhậtdữliệu • DataContext dataContext = new DataContext(liaConnectionString); • var ExpensiveBooks = • from b in dataContext.GetTable<Book>() • where b.Price>30 • select b; • foreach (Book b in ExpensiveBooks) • { • b.Price -= 5; • } • dataContext.SubmitChanges(); • Bộmôn HTTT

  30. LINQ – Truyvấn CSDL quanhệ(System.Data.Linq) Vídụ 3 – Thêmvàxóadữliệu DataContext dataContext = new DataContext(liaConnectionString); Table<Book> books = dataContext.GetTable<Book>(); Book newBook = new Book(); newBook.Price = 40; newBook.SubjectId = new Guid("a0e2a5d7-88c6-4dfe-a416-10eadb978b0b"); books.InsertOnSubmit(newBook); dataContext.SubmitChanges(); books.DeleteOnSubmit(newBook); dataContext.SubmitChanges(); • Bộmôn HTTT

  31. LINQ – Truyvấn CSDL quanhệ(System.Data.Linq) Vídụ 4 – Ánhxạlượcđồ CSDL quanhệvàmôhìnhlớpđốitượng • using System.Data.Linq.Mapping; • { • [Table] • public class Subject • { • [Column(IsPrimaryKey = true, Name = "ID")] • public Guid SubjectId { get; set; } • [Column] • public String Description { get; set; } • [Column] • public String Name { get; set; } • [Association(OtherKey="SubjectId")] • public EntitySet<Book> Books { get; set; } • } • } Cách 1: thểhiệnmốiánhxạngaytrựctiếptronglúcmôtảđốitượng (class) • Bộmôn HTTT

  32. LINQ – Truyvấn CSDL quanhệ(System.Data.Linq) Cách 2: thểhiệnmốiánhxạthông qua file XML môtả (giốngnhư Hibernate vàNhibernate) Vídụ 4 – Ánhxạlượcđồ CSDL quanhệvàmôhìnhlớpđốitượng • <?xml version="1.0" encoding="utf-16"?> • <Database Name="lia” xmlns="http://schemas.microsoft.com/linqtosql/mapping/2007"> • <Table Name="Author"> • <Type Name=“Common.Author"> • <Column Name="ID" Member="ID" Storage="_Id" • DbType="UniqueIdentifier NOT NULL" IsPrimaryKey="True" /> • <Column Name="LastName" Member="LastName" • DbType="VarChar(50) NOT NULL" CanBeNull="False" /> • <Column Name="FirstName" Member="FirstName" • DbType="VarChar(30)" /> • <Column Name="WebSite" Member="WebSite" • DbType="VarChar(200)" /> • <Column Name="TimeStamp" Member="TimeStamp" • DbType="rowversion NOT NULL" CanBeNull="False" • IsDbGenerated="True" IsVersion="True" AutoSync="Always" /> • </Type> • </Table> • </Database> • Bộmôn HTTT

  33. LINQ – Truyvấn CSDL quanhệ(System.Data.Linq) Cách 2: thểhiệnmốiánhxạthông qua file XML môtả (giốngnhư Hibernate vàNhibernate) Vídụ 4 – Ánhxạlượcđồ CSDL quanhệvàmôhìnhlớpđốitượng XmlMappingSource map = XmlMappingSource.FromXml(File.ReadAllText(@"lia.xml")); DataContext dataContext = new DataContext(liaConnectionString, map); Table<Author> authors = dc.GetTable<Author>(); • Bộmôn HTTT

  34. LINQ – Truy vấn XML(System.XML.Linq) • XLINQ: • Là bộ hàm thư viện API dùng để truy vấn XML • Là tập các lớp đặc biệt cho phép thể hiện các thẻ trong tài liệu XML theo dạng đối tượng. Do vậy có thể truy vấn trực tiếp XML thông qua LINQ • Bộmôn HTTT

  35. LINQ – Truy vấn XML(System.XML.Linq) • Bộmôn HTTT

  36. LINQ – Truy vấn XML(System.XML.Linq) Vídụ 1 – Tạo file XML • Cách 1: • XElement books = new XElement("books", • new XElement("book", • new XElement("title", "LINQ in Action"), • new XElement("author", "Steve Eichert"), • new XElement("author", "Jim Wooley"), • new XElement("author", "FabriceMarguerie") • ) • ); • books.Save(@"c:\books.XML"); • Cách 2: • XElement book = new XElement("book"); • book.Add(new XElement("author", "Don Box")); • book.Add(new XElement("title", "Essential .NET")); • XElement books = new XElement("books"); • books.Add(book); • books.Save(@"c:\books.XML"); • Bộmôn HTTT

  37. LINQ – Truy vấn XML(System.XML.Linq) Vídụ 2 – Nạp file vàPhântíchchuỗi XML • Nạp file: • XElement x = XElement.Load(@"c:\books.xml"); • XElement x = XElement.Load("http://msdn.microsoft.com/rss.xml"); • Phântíchchuỗi • XElement x = XElement.Parse( • @"<books> • <book> • <author>Don Box</author> • <title>Essential .NET</title> • </book> • <book> • <author>Martin Fowler</author> • <title>Patterns of Enterprise Application Architecture</title> • </book> • </books>"); • Bộmôn HTTT

  38. LINQ – Truy vấn XML(System.XML.Linq) Vídụ 3 – Thêm, xóa, sửanội dung Thêm: XElement book = new XElement("book"); book.Add(new XElement("author", "Dr. Seuss")); Xóa: books.Element("book").Remove(); // remove the first book books.Elements("book").Remove(); // remove all books Sửa: XElement books = new XElement("books.xml"); books.Element("book").SetElementValue("author", "Bill Gates"); • Bộmôn HTTT

  39. LINQ – Truy vấn XML(System.XML.Linq) Vídụ 4 – Truyvấn • Ví dụ 1 • var query = from p in people • where p.CanCode • select new XElement("Person", • new XAttribute("Age", p.Age), • p.Name); • Ví dụ 2 • IEnumerable<string> justNames = • from e in x.Descendants("Person“) • select e.Value; • Ví dụ 3 • IEnumerable<Person> persons = • from e in x.Descendants("Person“) • select new Person { • Name = e.Value, • Age = (int?)e.Attribute("Age") ?? 21 • }; • Bộmôn HTTT

  40. LINQ – Truy vấn XML(System.XML.Linq) Vídụ 5 – HỗtrợXPath • XElement root = XElement.Load("categorizedBooks.xml"); • var books = from book in root.XPathSelectElements("//book") • select book; • foreach(XElement book in books) { • Console.WriteLine((string)book); • } • Bộmôn HTTT

  41. LINQ – Truy vấn XML(System.XML.Linq) Vídụ 6 – Hỗtrợchuyểnđổitàiliệu • XLINQ cho phép hỗ trợ chuyển đổi tài liệu XML to XML, XML to HTML (XSLT) • Ánh xạ giữa mô hình đối tượng với XML • Ánh xạ giữa mô hình CSDL quan hệ với XML • Bộmôn HTTT

  42. Tài liệu tham khảo Các trang web: 1/ www.microsoft.com 2/ www.codeproject.com 3/ www.csharpconner.com 4/ www.google.com Các tài liệu ebook: 1/ Manning.LINQ.in.Action (Jan.2008) FABRICE MARGUERIE , STEVE EICHERT, JIM WOOLEY 2/ Pro LINQ Language Integrated Query in C# 2008 Joseph C. Rattz Các tài liệu khác: 1/ MSDN 2008 2/ Visual Studio Team Edition 2008 • Bộmôn HTTT

  43. Lời cảm ơn • Xinchânthànhcảmơnđãlắngnghevàgóp ý • Bộmôn HTTT

More Related